webpack 打包nodejs项目

今天使用webpack打包nodejs项目时,报了一大堆(类似下面)的错,经过分析和谷歌搜索也没有找到答案,我想这一定是没有找到重点,姿势不对。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ERROR in ./node_modules/mongodb/lib/command_cursor.js 6:15-41
Module not found: Error: Can't resolve 'stream' in '/Users/huosj/Documents/workspace/wt-gaea/node_modules/mongodb/lib'

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: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
@ ./node_modules/mongodb/lib/apm.js 6:18-45 297:4-41
@ ./node_modules/mongodb/index.js 3:20-40
@ ./ts-build/server/kernel/constants.js 4:16-34

后来根据一个比较了解webpack的同事给出的指导,才知道这个问题的重点
是 webpack 打包 nodejs常见的问题,因为nodejs对于webpack来说是外部扩展,意思就是webpack不会内置nodejs,所以解决办法就是 忽略nodejs的环境

在配置中添加:

1
2
3
4
5
6
7
8
9
const nodeExternals = require('webpack-node-externals');
module.exports = {
target: "node",
externals: [
nodeExternals({
allowlist: ['webpack/hot/poll?100'],
}),
]
};

更多详情:

原创技术分享,您的支持将鼓励我继续创作