Angular 18安装google-auth-library后ng serve遇Webpack polyfill报错求助
你遇到的报错是因为 webpack 5 不再默认提供 Node.js 核心模块的 polyfill,而 google-auth-library 依赖了这些模块。Angular 默认没有暴露 webpack 配置文件,需要通过自定义 webpack 来解决,步骤如下:
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 }
1. 安装依赖
先装自定义 webpack 构建工具和所需的 polyfill 包:
npm install @angular-builders/custom-webpack --save-dev npm install path-browserify browserify-zlib stream-browserify util buffer --save
2. 新建 webpack 配置文件
在项目根目录创建 webpack.config.js,配置如下:
module.exports = { resolve: { fallback: { "path": require.resolve("path-browserify"), "fs": false, // 浏览器环境不需要文件系统模块,直接禁用 "http2": false, "zlib": require.resolve("browserify-zlib"), "stream": require.resolve("stream-browserify"), "util": require.resolve("util"), "buffer": require.resolve("buffer/") } }, plugins: [ // 全局注入 Buffer,避免库内部找不到 new require('webpack').ProvidePlugin({ Buffer: ['buffer', 'Buffer'], }) ] };
3. 修改 Angular 构建配置
打开 angular.json,找到你项目的 architect 配置:
- 将
build的 builder 替换为@angular-builders/custom-webpack:browser - 将
serve的 builder 替换为@angular-builders/custom-webpack:dev-server - 在
build的options中添加自定义配置:
"options": { "customWebpackConfig": { "path": "./webpack.config.js" }, // 保留原有其他配置... }
4. 补充全局 polyfill(按需)
如果启动后仍报 Buffer 相关错误,打开 src/polyfills.ts 加入:
import 'buffer'; (window as any).Buffer = window.Buffer;
完成以上步骤后,重新运行 ng serve 即可正常启动项目。
内容的提问来源于stack exchange,提问作者miles_holt

