为什么 webpack 不摇树 swiperjs 模块?
Why isn't webpack tree-shaking swiperjs modules?
所以,swiperjs,来自文档:
"默认情况下,Swiper 仅导出核心版本,没有附加模块(如导航、分页等)。因此您也需要导入和配置它们:"
// core version + navigation, pagination modules:
import Swiper, { Navigation, Pagination } from 'swiper';
嗯,我做到了。这是我的 index.js 测试文件:
import Swiper, { Navigation, Pagination } from 'swiper';
console.log(Swiper);
这是我的 webpack 配置:
const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
//mode: 'development',
mode: 'production',
watch: true,
entry: {
index: './src/index.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
optimization: {
minimize: true,
usedExports: true,
}
plugins: [
new BundleAnalyzerPlugin()
],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: { presets: ['@babel/preset-env'] }
}
} // babel
] // rules
} // module
};
好吧,BundleAnalyzer 图表显示所有 swiper 模块都已捆绑。为什么?我怎样才能避免这种情况?
我已经从 package.json 禁用了 sideEffect
并在优化中激活了 providedExports
。
swiper.esm.js的源码复制在这里供参考:https://jsfiddle.net/fw4zj8qk/
我发现了问题:对于 swiper(至少),sideEffects 选项必须在加载器级别而不是包级别使用。或者您可以在包级别使用,但显式声明文件。虽然没有尝试。
相反,它确实通过像这样设置 sideEffects 来工作:
module: {
rules: [
// [...] here normally there are babel settings and the like
{ // here doing the swiper loader and declaring no sideEffects
test: /swiper\.esm\.js/,
sideEffects: false
}
] // rules
} // module
现在 swiper 得到 tree shaking。
所以,swiperjs,来自文档:
"默认情况下,Swiper 仅导出核心版本,没有附加模块(如导航、分页等)。因此您也需要导入和配置它们:"
// core version + navigation, pagination modules:
import Swiper, { Navigation, Pagination } from 'swiper';
嗯,我做到了。这是我的 index.js 测试文件:
import Swiper, { Navigation, Pagination } from 'swiper';
console.log(Swiper);
这是我的 webpack 配置:
const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
//mode: 'development',
mode: 'production',
watch: true,
entry: {
index: './src/index.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
optimization: {
minimize: true,
usedExports: true,
}
plugins: [
new BundleAnalyzerPlugin()
],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: { presets: ['@babel/preset-env'] }
}
} // babel
] // rules
} // module
};
好吧,BundleAnalyzer 图表显示所有 swiper 模块都已捆绑。为什么?我怎样才能避免这种情况?
我已经从 package.json 禁用了 sideEffect
并在优化中激活了 providedExports
。
swiper.esm.js的源码复制在这里供参考:https://jsfiddle.net/fw4zj8qk/
我发现了问题:对于 swiper(至少),sideEffects 选项必须在加载器级别而不是包级别使用。或者您可以在包级别使用,但显式声明文件。虽然没有尝试。 相反,它确实通过像这样设置 sideEffects 来工作:
module: {
rules: [
// [...] here normally there are babel settings and the like
{ // here doing the swiper loader and declaring no sideEffects
test: /swiper\.esm\.js/,
sideEffects: false
}
] // rules
} // module
现在 swiper 得到 tree shaking。