本文的目标是解决以下问题:
如何在打包时去掉node_modules
备注:共5个可选方案,推荐方案5
【方案1】: 使用webpack-node-externals(验证OK)
具体实现:采用webpack-node-externals,打包中去掉node_modules中的依赖库
npm install webpack-node-externals --save-dev
var nodeExternals = require(‘webpack-node-externals’);
var nodeExternals = require(‘webpack-node-externals’);
资料截图
可参考webpack-node-externals的帮助:https://github.com/liady/webpack-node-externals
**【方案2】**使用externals的function配置方式(验证OK)
具体实现:通过制定包名称排除指定的包
function getExternals() {
return {
"ant-design-vue": "ant-design-vue",
"core-js": "core-js",
echarts: "echarts",
"echarts-liquidfill": "echarts-liquidfill",
vue: "vue",
"vue-router": "vue-router",
vuex: "vuex",
"vue-i18n": "vue-i18n",
"whatwg-fetch": "whatwg-fetch",
"js-cookie": "js-cookie",
"videojs-contrib-hls": "videojs-contrib-hls",
"vue-grid-layout": "vue-grid-layout",
"vue-video-player": "vue-video-player",
"vue-baidu-map": "vue-baidu-map",
"vue-color": "vue-color",
};
}
configureWebpack: {
externals: process.env.NODE_ENV === "production" ? getExternals() : { echarts: "echarts", zrender: "zrender" },
},
**【方案3】**使用externals的function配置方式(初步验证无效)
具体实现:通过指定路径
const fs = require(“fs”);
function getExternals() {
var exts = {};
fs.readdirSync(__dirname + "/node_modules").forEach(function(item) {
// 我没有使用es6
if (item.indexOf(".") === 0) return;
exts[item] = "commonjs " + item;
});
return exts;
}
configureWebpack: {
externals: process.env.NODE_ENV === "production" ? getExternals() : { echarts: "echarts" },
},
**【方案4】**使用externals的reg方式(待验证)
configureWebpack: {
externals: process.env.NODE_ENV === "production" ? /^[a-z\-0-9]+$/ : { echarts: "echarts" },
},
**【方案5】**webpack-node-externals和对象混合使用(推荐,自己采用的方式)
适合echarts等库单独打包的场景(即echarts不通过node_modules中引入)
var nodeExternals = require(“webpack-node-externals”);
configureWebpack: {
externals:
process.env.NODE_ENV === "production" ? [nodeExternals(), { echarts: "echarts", zrender: "zrender" }] : { echarts: "echarts", zrender: "zrender" },
},
了解更多内容 关注公众号