lukejacksonn / servor

Dependency free file server for single page app development
MIT License
1.04k stars 70 forks source link

Adds --module flag for loading es modues directly #48

Closed lukejacksonn closed 4 years ago

lukejacksonn commented 4 years ago

Currently servor's default behaviour is to redirect non-file requests to index.html but a lot of the time when prototyping apps now I find myself creating a html file containing just:

<script src="./index.js" type="module">

The file index.js usually imports some modules, does some computation and either logs to the console or renders content into the document body. For example:

import { react, html, css } from 'https://unpkg.com/rplus';

const app = () => {
  const [get, set] = react.useState(null);
  react.useEffect(() => {
    set(Math.random())
  }, []);
  return get ? html `<h1>${get}</h1>` : null;
}

console.log('Started the application!');
react.render( html`<${app} />`,  document.body);

The changes in this PR makes it so that if the --module flag is passed then servor will serve `index.js (with the following transformation) in response to non-file requests.

if (isRoute && module) {
  file = `<!DOCTYPE html><meta charset='utf-8'/><script type='module'>${file}</script>`;
  ext = 'html';
}

It wraps the contents of the file in markup and changes the extension to html. This forces the browser to evaluate the module. This will only work with entry points that describe their dependency tree using the es module syntax (no cjs or require).

lukejacksonn commented 4 years ago

Merged in with #51