Skip to content

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

@ColmBhandal

Description

@ColmBhandal

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions