@idio/frontend
![npm version](https://badge.fury.io/js/%40idio%2Ffrontend.svg)
@idio/frontend
is The Middleware To Serve Front-End JavaScript. It allows to set-up the modern front-end development environment where node_modules
are served alongside compiled JSX code (without using Babel, see @a-la/jsx
).
yarn add -E @idio/frontend
Table Of Contents
![](https://github.com/idiocc/frontend/raw/HEAD/.documentary/section-breaks/0.svg?sanitize=true)
API
The package is available by importing its default function:
import frontend from '@idio/frontend'
![](https://github.com/idiocc/frontend/raw/HEAD/.documentary/section-breaks/1.svg?sanitize=true)
async frontend(
config: FrontendConfig,
): Middleware
The middleware constructor will initialise the middleware function to serve files from the specified directory (frontend
by default). The files will be updated on-the-fly to fix their imports to relative paths (e.g., preact
will be transformed into /node_modules/preact/dist/preact.mjs
). Any CSS styles will also be served using an injector script.
FrontendConfig
: Options for the middleware.
Name | Type | Description | Default |
---|
directory | string | The directory from which to serve files. | frontend |
pragma | string | The pragma function to import. This enables to skip writing h at the beginning of each file. JSX will be transpiled to have h pragma, therefore to use React it's possible to do import { createElement: h } from 'react' . | import { h } from 'preact' |
The middleware can be used in any Koa
application, or within the idio
web server.
import core from '@idio/core'
import render from 'preact-render-to-string'
import frontend from '@idio/frontend'
(async () => {
const { url, router, app } = await core({
logger: { use: true },
_frontend: {
use: true,
middlewareConstructor(_, config) {
return frontend(config)
},
config: {
directory: 'example/frontend',
},
},
})
router.get('/', async (ctx) => {
ctx.body = '<!doctype html>\n' + render(
<html>
<head><title>Example</title></head>
<body>
Hello World
<script type="module" src="example/frontend"/>
</body>
</html>)
})
app.use(router.routes())
console.log('Started on %s', url)
})()
example/frontend
├── Component.jsx
├── index.jsx
└── style.css
The entry point
import { render } from 'preact'
import Component from './Component'
import { Form, Input } from '@depack/form'
render(<Component test="Welcome"/>, document.body)
render(<Form>
<Input placeholder="hello world"/>
</Form>, document.body)
The component
import './style.css'
const Component = ({ test }) => {
return <div>{test}</div>
}
export default Component
The style
body {
background: lightcyan;
}
![Chrome Example](https://github.com/idiocc/frontend/raw/HEAD/docs/Example1.gif)
![](https://github.com/idiocc/frontend/raw/HEAD/.documentary/section-breaks/2.svg?sanitize=true)
Copyright
![](https://github.com/idiocc/frontend/raw/HEAD/.documentary/section-breaks/-1.svg?sanitize=true)