webpack碎片化知识记录

13 阅读1分钟

tree-shaking

webpack在生产环境编译时,会自动剔除掉那些没有使用到的方法或者变量:

打包前:

app.js 导出了2个方法:

export const add = (a, b) => {
  return a + b;
};
export const subtract = (a, b) => {
  return a - b;
};

index.js 只引入了一个 add

import { add } from "./app";
console.log(add(4, 5));

打包后:只打印了结果,webpack把精简做到了极致,以便减小包的体积

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

# Shimming 预置依赖

某些第三方插件需要全局使用,比如jquery等;

webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports={
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html",
      filename: "index.html",
      inject: "body",
    }),
    //把需要全局暴露的模块添加
    new webpack.ProvidePlugin({
      _: "lodash",
    }),
  ],

}

使用: 在使用时,直接用 ProvidePlugin 中声明的变量即可;

let res=_.map([1, 2, 3], (x) => x * 2)