今天使用webpack打包nodejs项目时,报了一大堆(类似下面)的错
ERROR in ./node_modules/_inflation@2.0.0@inflation/index.js 2:11-26
Module not found: Error: Can't resolve 'zlib' in 'E:\comproject\projecrt-server\node_modules\_inflation@2.0.0@inflation'
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: { "zlib": require.resolve("browserify-zlib") }'
- install 'browserify-zlib'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "zlib": false }
@ ./node_modules/_co-body@6.1.0@co-body/lib/text.js 8:16-36
@ ./node_modules/_co-body@6.1.0@co-body/index.js 6:0-36
@ ./node_modules/_koa-bodyparser@4.3.0@koa-bodyparser/index.js 17:12-30
@ ./app.ts 9:19-44
@ ./bin/www.ts 6:13-30
后来搜索了一翻 发现是 webpack 打包 nodejs常见的问题,因为nodejs对于webpack来说是外部扩展,意思就是webpack不会内置nodejs,所以解决办法就是 忽略nodejs的环境。
所以需要在打包的时候给webpack当前的环境,搜索到的配置代码为
const nodeExternals = require('webpack-node-externals');
module.exports = {
target: "node",
externals: [
nodeExternals({
allowlist: ['webpack/hot/poll?100'],
}),
]
};
但是我在实际运用的时候 发现只要给定target: "node"就可以了,如果不行的话,建议也装上依赖