You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 18安装google-auth-library后ng serve遇Webpack polyfill报错求助

Angular 安装 google-auth-library 后 webpack 5 模块缺失问题解决

你遇到的报错是因为 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:11:12