Using Node.js require vs. ES6 import/export

后端 未结 10 791
醉酒成梦
醉酒成梦 2020-11-22 05:19

In a project I\'m collaborating on, we have two choices on which module system we can use:

  1. Importing modules using require, and exporting using
10条回答
  •  误落风尘
    2020-11-22 05:31

    Using ES6 modules can be useful for 'tree shaking'; i.e. enabling Webpack 2, Rollup (or other bundlers) to identify code paths that are not used/imported, and therefore don't make it into the resulting bundle. This can significantly reduce its file size by eliminating code you'll never need, but with CommonJS is bundled by default because Webpack et al have no way of knowing whether it's needed.

    This is done using static analysis of the code path.

    For example, using:

    import { somePart } 'of/a/package';
    

    ... gives the bundler a hint that package.anotherPart isn't required (if it's not imported, it can't be used- right?), so it won't bother bundling it.

    To enable this for Webpack 2, you need to ensure that your transpiler isn't spitting out CommonJS modules. If you're using the es2015 plug-in with babel, you can disable it in your .babelrc like so:

    {
      "presets": [
        ["es2015", { modules: false }],
      ]
    }
    

    Rollup and others may work differently - view the docs if you're interested.

提交回复
热议问题