Skip to content

klesun/ts-browser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

92 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ts-browser

Run typescript files with imports on the fly. Like ts-node, but for browser.

Perfect fallback solution for environments that are only supposed to host static source files (like GitHub Pages).

Usage: (sample project)

<!-- index.html -->
<script type="module">
    import {loadModule} from 'https://klesun.github.io/ts-browser/src/ts-browser.js';
    // language=file-reference
    const entryScriptPath = './index.ts';
    loadModule(entryScriptPath).then(indexModule => {
        return indexModule.default(document.getElementById('composeCont'));
    });
</script>
// index.ts
import {makePanel} from './utils/SomeDomMaker';

export default (composeCont) => {
    composeCont.appendChild(makePanel());
};

You can also use it with .tsx files:

https://github.com/klesun-misc/ts-browser-react-example/blob/master/index.html

https://klesun-misc.github.io/ts-browser-react-example/

<script type="module">
    import {loadModule} from 'https://klesun.github.io/ts-browser/src/ts-browser.js';
    // language=file-reference
    const entryScriptPath = './app.tsx';
    loadModule(entryScriptPath, {
        jsx: 2, // ts.JsxEmit.React
    });
</script>

I highly recommend you to also use the @typescript-eslint/consistent-type-imports eslint rule to make sure that no redundant http requests will be performed for type-only imports

The script uses typescriptServices.js to parse ts file for dependencies and transpile it to js.

Each file loads about 10-50 milliseconds. Some basic optimization is applied during compilation, like using web workers and storing compilation results in window.localStorage, not sure if it can be optimised further, would need research.

The behaviour on circular dependencies may be not what you expect: I tried to mimick typescript's behaviour (which allows circular dependencies) by creating a Proxy object for the module which throws errors if you attempt to access a field before module fully loaded. If this appears to be inconsistent, you can file an issue with minimal example - I'll think of a better way to implement circular dependencies then.

There was a similar project once, called typescript-script, but it was last updated 5 years ago, did not manage to get it working, and it does not seem to load dependencies.


If you prefer npm:

npm install ts-browser-klesun
import {loadModule} from './node_modules/ts-browser-klesun/src/ts-browser.js';

(it's called ts-browser-klesun in npm, don't confuse with ts-browser which does a similar job, but by listing dependencies in the html file, not with import-s)

About

Run typescript files with imports on the fly. Like ts-node, but for browser

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published