Skip to content

Instantly share code, notes, and snippets.

@cancerberoSgx
Created July 12, 2018 23:20
Show Gist options
  • Save cancerberoSgx/2151d205c4aa13a7973cf25dd8e396d6 to your computer and use it in GitHub Desktop.
Save cancerberoSgx/2151d205c4aa13a7973cf25dd8e396d6 to your computer and use it in GitHub Desktop.
import Project from "ts-simple-ast";
const project = new Project({ useVirtualFileSystem: true });
const file = project.createSourceFile("src/a.ts", `
export class A {
method1(msg: string): string {
return "hello " + name;
}
}`);
file.getClassOrThrow("A").getMembers().forEach(m => console.log(m.getKindName()));
/*
# build a ts-simple-ast bundle.js for the browser with browserify
The code above uses virtualFileSystem and it will work in the browser out of the box. We just need to run browserify in our project:
```sh
tsc # assume it emits .js files to dist folder
npx browserify -e dist/index.js -o dist/bundle.js
```
# Minify
```sh
google-closure-compiler --js=dist/bundle.js --js_output_file=dist/bundle.min.js
```
We can exclude some unneeded dependencies manually to reduce the bundle size a little bit:
```sh
npx browserify -e dist/index.js -o dist/bundle.js -i fs.realpath -i fs-extra -i dir-glob -i graceful-fs -i fast-glob -i fs -i source-map-support -i globby -i glob-parent -i glob
```
## Exclude TypeScript if already loaded
bundle.js will contain the whole typescript.js file. If you are already loading it in your page and you are sure/responsible is compatible with the version required by ts-simple-ast it could be a good idea to exclude this will reduce output size by 50% or more:
```sh
tsc
npx browserify -x typescript -e dist/index.js -o dist/bundle.js
```
Feedback:
* useVirtualFileSystem will work in the browser - no need to implement FileSystemHost from scratch
* Missing documentation - I could write a couple of paragraphs but I'm not sure in which section, perhaps in filesystem's?
* Would be good idea to export VirtualFileSystemHost so users can override a couple of them to support, for ex, indexDB or reuse it even for other techs besides the browser. Document its methods stating that async ones are based on syncs (so users override only those) and also change modifiers of some attributes (directories) from private to protected so subclasses have visibility
* I've seen some libraries in similar situation (eslint) distribute a browser bundle or provide npm run build-browser script. is easy to do but I'm not sure is worthwhile for ts-simple-ast since I need to add browserify or webpack devDependency.
* tests ? (again IMO not worthwhile )
* future : better dependency injection - DefaultFileSystemHost is required and used in some places directly (LanguageServiceHost). Probably this could be easily solved with a factory
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment