webpack5+crypto

测试 webpack 5 兼容性

webpack4 有以下设置

  node: {
    Buffer: false,
    process: false,
  },

而webpack 5 从配置中移除了这些选项,并始终赋值 false。
那么 在项目中使用了 node 内置模块应该怎么配置?

例如项目中 使用了crypto

const crypto = require('crypto')

运行后报错:

Module not found: Error: Can't resolve 'crypto' in 'xxx'

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: { "crypto": require.resolve("crypto-browserify") }'
	- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
	resolve.fallback: { "crypto": false }

解决方法一:
安装 crypto-browserify

npm install crypto-browserify

import crypto from 'crypto-browserify'

解决方法二:
webpack 打包配置增加 一个fallback 来处理 crypto模块的问题:

resolve: {
    fallback:{
        'crypto': require.resolve('crypto-browserify')
    }
},