Vue打包优化:打包去掉node_modules最佳方案

本文的目标是解决以下问题:

如何在打包时去掉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" },

},

了解更多内容 关注公众号

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值