aws-sam-webpack-plugin icon indicating copy to clipboard operation
aws-sam-webpack-plugin copied to clipboard

Remove `"module": "commonJS"` in TSConfig Example to support Tree Shaking?

Open ColmBhandal opened this issue 2 years ago • 0 comments

In README.md, we are given an example tsconfig.json for setting this project up with Typescript. Inside that config file, the module type is set as follows:

"module": "commonJS"

However, according to the Webpack docs on ts-loader:

ts-loader uses tsc, the TypeScript compiler, and relies on your tsconfig.json configuration. Make sure to avoid setting module to "CommonJS", or webpack won't be able to tree-shake your code.

So maybe the example tsconfig.json should omit "module": "commonJS", to foster best practices?


I haven't thoroughly tested this, but at a glance it seems like omitting "module": "commonJS" is fine - Webpack still packs the file into common JS anyway. I guess what Webpack is doing is as follows:

  • First, call the Typescript transpiler
  • Then, do the normal Webpack stuff on the transpiled files

I guess the "normal Webpack stuff" already creates common JS modules, so there is no need to do the conversion to common JS during TS transpilation; in fact, as documented, doing so seems to break tree-shaking because Webpack can't tree-shake dynamic imports. It can only tree shake ES modules.


Compilation seems to work with or without "module": "commonJS", with slightly different resulting output. So it doesn't seem to be a deal breaker either way. But it's probably best to align with the Webpack docs on "module": "commonJS". As it stands, if the reasoning outlined so far is correct, most people will likely copy the example from the README and inadvertently miss out on tree-shaking.

ColmBhandal avatar Jul 18 '22 14:07 ColmBhandal