摇树(tree shaking)
我主要是想说摇树失败的原因(tree shaking 失败的原因),先讲下摇树本身效果
什么是摇树?
举个例子
首先 webpack.config.js配置
const webpack = require("webpack");
/**
* @type {webpack.Configuration}
*/
module.exports = {
mode: "production"
};
在固定 a.js 用esm导出,b.js用commonjs导出不变动
// a.js
export function f1() {
console.log("11111");
}
export function f2() {
console.log("22222");
}
// b.js
exports.f3 = function () {
console.log("33333");
};
exports.f4 = function () {
console.log("44444");
};
例子1:import a.js 和 require b.js
// index.js
import {
f1 } from "./a";
import {
f3 } from "./b";
console.log(f1);
console.log(f3);
打包结果:a.j 和 b.js 都摇树了,只输出了 f1 和 f3。所以导入用import,导出esm和commonjs都可以
例子2:import a.js 和 import b.js
// index.js
import {
f1 } from "./a";
const {
f3 } = require("./b");
console.log(f1);
console.log(f3)<