Most users will configure the TypeScript compiler to use
But Webpack will not be able to do tree shaking anymore as it will only see
require instead of ES6
Code splitting would still be possible, if you use Webpack’s proprietary
require.ensure, but this is not a nice solution: Your IDE won’t be able to give type information anymore.
To solve this, you should choose
"esnext" as a target and as a
Basically what you need is, that the TypeScript compiler does not change anything, but also strips TypeScript typing information from the code.
To achieve that, the important configuration in your
tsconfig.json should look like this:
With the preset
babel-preset-env you just define what browser you want to support. The preset
babel-preset-env will configure Babel to precisely transpile only what needs to be transpiled to run in the browsers you chose. Your
.babelrc should look somewhat like this:
Two important things to notice here: You must tell
babel-preset-env to not touch the modules, meaning it will just keep import statements like
import a from './b' as they are.
In addition you have to add
babel-plugin-syntax-dynamic-import as plugin to keep dynamic import statements like
const a = await import('./b') untouched.
As final step, we have to configure Webpack accordingly.
You would use your
awesome-typescript-loader as usual, but add the
useBabel: true option (which is the same as prepending the
babel-loader in the rules chain).
The important parts of your
webpack.config.js would look like this:
babel-preset-env instead of letting TypeScript do the whole compilation.
Let’s wrap up with a brief overview of what had to be done:
- Configure TypeScript compiler to leave code more or less untouched by using
- Add Babel configuration to transpile with
babel-preset-envpreset while not touching imports or dynamic imports.
- Tell Webpack to use TypeScript + Babel, either by configuring
awesome-typescript-loaderor by manually adding
To see everything in action, I prepared a demo repository.