问题背景:
在项目里使用了express库做前端的服务器,结果一运行给我报了23个errors(悲)
ERROR in ./node_modules/serve-static/index.js 19:14-37
Module not found: Error: Can't resolve 'path' in 'D:\project\vue2\vue-permission-demo\node_modules\serve-static'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
@ ./node_modules/express/lib/express.js 81:0-40
@ ./node_modules/express/index.js 11:0-41
@ ./src/utils/http.js 8:0-35 66:29-37
@ ./src/api/index.js 1:0-34 10:9-18
@ ./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/@vue/vue-loader-v15/lib/index.js??vue-loader-options!./src/pages/login/index.vue?vue&type=script&lang=js& 1:0-34 12:23-28
@ ./src/pages/login/index.vue?vue&type=script&lang=js& 1:0-205 1:221-224 1:226-428 1:226-428
@ ./src/pages/login/index.vue 2:0-57 3:0-52 3:0-52 10:2-8
@ ./src/router/index.js 3:0-35 14:13-18
@ ./src/main.js 4:0-30 9:2-8
webpack compiled with 23 errors
问题定位
可以发现这23个错大部分都是“Module not found”,经查询后发现在webpack5中移除了nodejs核心模块的polyfill自动引入,那么就会造成包的缺失。
解决方法
1、运行下面这行指令,安装在 Webpack 中 Polyfill Node.js 核心模块。
npm install node-polyfill-webpack-plugin
2、在vue.config.json中进行对webpack的配置
//头部引用
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
//加入
configureWebpack: {
plugins: [new NodePolyfillPlugin()]
}
3、在vue.config.json中手动添加(如果第2步做完后还有报错的话)
即说白了就是在externals中手动引入缺的模块
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
module.exports = {
//调整内部的 webpack 配置
configureWebpack: {
plugins: [new NodePolyfillPlugin()],
externals: {
fs: require('fs'),
net: require('net'),
async_hooks: require('async_hooks')
}
},
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3300',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}