简体   繁体   中英

Tree-shaking TypeScript/JavaScript shared between browser and Node

I'm working on a TypeScript project that contains various modules shared between a browser client and a Node-based server. We'd like to bundle and tree-shake the modules with webpack/rollup for the browser, which requires configuring the TypeScript compiler to target ES6 in order to preserve imports. However, to run on Node, we need to target ES5, which turns imports into requires and thus prevents tree-shaking.

Is there an elegant way to solve this without compiling everything twice, once to ES5 and again to ES6?

Possible solutions are:

.1 In both cases target single ES6, but in Node case use additional Rollup step with external option enabled and target ES5. In that case tsc guarantees removing of all type annotations and other type-related stuff, then Rollup does heavy lifting by transforming ES6 → ES5 and tree-shaking stuff. You'll need Rollup's JavaScript API, since CLI API only supports external = string[] with concrete modules, but you'll need to «external all». In that case JavaScript API: external: (id) => id != main_file .

downsides :

  • in that case you can't use Rollup CLI API, you'll need to write script

.2 Use Rollup as a main player and rollup-plugin-typescript to generate two different targets with Rollup: ES5 and ES6. Generating many targets from one bundle is pretty simple in Rollup.

downsides :

  • rollup-plugin-typescript, even if officially living under Rollup's org wing, is developed very slow. I can't characterize it as «stable».

.3 Generate ES6 only and use ESM for Node target. You can learn more by link, but in fact this already works well and performance shall be OK .

downsides :

  • supplying ESM require patcher to Node target (simple)

.4 If your main issue with «compiling everything twice» is speed, then do full build (even if it twice build) only in production. You can introduce some simple script, doing only required actions in dev and leveraging tsc 's (or Rollup's) --watch ability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM