How to make a class-based custom element side-effect-free so webpack only bundles the explicitly imported components

﹥>﹥吖頭↗ 提交于 2019-12-03 07:01:35

From webpack guide - Mark the file as side-effect-free:

All the code noted above does not contain side effects, so we can simply mark the property as false to inform webpack that it can safely prune unused exports.

So, setting "sideEffects": false in package.json tells webpack that your modules are side effect free. So that it can prune unused exports (in your case, unused re-exports). This is generally used by library authors.

But that's just one side of the equation.

From webpack configuration docs - optimization.sideEffects:

Tells webpack to recognise the sideEffects flag in package.json or rules to skip over modules which are flagged to contain no side effects when exports are not used.

So, in order to leverage that previously mentioned option, the library consumer will have to set the optimization.sideEffects option to true in their webpack config file:

// webpack.config.js
module.exports = {
  ...
  optimization: {
    sideEffects: true
  }
  ...
}

Note that, in production mode, this option is enabled by default. So, you'll only need to set it for development mode.

N.B.: In this case, you are both the author and the consumer of your modules.

Lastly, let's look at your webpack entrypoint:

// webpack entrypoint
import 'document-register-element';
import 'babel-polyfill';
import { CompDiv } from './index';

If you don't use your imported CompDiv later in this file, webpack will prune it - assuming you've set "sideEffects": false in package.json and optimization.sideEffects to true in your webpack config.

But, for example, even if you only imported 'babel-polyfill' and won't explicitly use anything from it later in this file, webpack will not prune it, because the package.json for babel-polyfill library doesn't contain "sideEffects": false.

I hope that clears things up.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!