将文件标记为 side-effect-free(无副作用)

276 阅读1分钟

需要将 mode 配置设置成 development,以确定 bundle 不会被压缩:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
 mode: 'development',
 optimization: {
   usedExports: true,
 },
};

src/title.js

document.title = "改标题";
export function getTitle() {
  console.log("getTitle");
}

src/index.js

import './title.js'
console.log('hello world')

bundle.js

(()=>{"use strict";document.title="改标题",console.log("hello world")})();

发现保留了代码 document.title="改标题" ,如果想这行代码也被 Tree Shaking 删除掉,可以在 package.json 文件中加上 "sideEffects": false, 这个配置,然后重新打包就没有这行代码了。

(()=>{"use strict";console.log("hello world")})();

注意,将文件标记为 side-effect-free(无副作用) ,所有导入文件都会受到 tree shaking 的影响。如果在项目中使用类似 css-loader 并 import 一个 CSS 文件,将会在生产模式中删除。

src/index.css

html,body {
  background: red;
}

src/index.js

import './index.css'

console.log('hello world')

bundle.js

(()=>{"use strict";console.log("hello world")})();

发现打包的时候 index.css 的样式并没有打包进来。现在可以通过修改 sideEffects 配置选项,来设置CSS文件打包的时候取消 Tree Shaking 的影响。

sideEffects:["*.css"]

此数组支持简单的 glob 模式匹配相关文件。其内部使用了 glob-to-regexp(支持:***{a,b}[a-z])。如果匹配模式为 *.css,且不包含 /,将被视为 **/*.css