【问题标题】:Angular 6 - process is not defined when trying to serve applicationAngular 6 - 尝试为应用程序提供服务时未定义进程
【发布时间】:2018-05-13 07:26:39
【问题描述】:

当我尝试使用 cosmicjs 为我的 Angular 6 应用程序提供服务时出现以下错误:

Uncaught ReferenceError: process is not defined
    at Object../node_modules/cosmicjs/dist/index.js (index.js:6)
    at __webpack_require__ (bootstrap:81)
    at Object../src/app/app.component.ts (main.js:94)
    at __webpack_require__ (bootstrap:81)
    at Object../src/app/app.module.ts (app.component.ts:9)
    at __webpack_require__ (bootstrap:81)
    at Object../src/main.ts (environment.ts:18)
    at __webpack_require__ (bootstrap:81)
    at Object.0 (main.ts:12)
    at __webpack_require__ (bootstrap:81)

我的最新理论与未定义的 process.env 属性有关。

我正在关注这个教程here

我的确切代码可以在here找到

本教程似乎使用的是旧版本的 angular,它使用 .angular-cli.json 而不是新的 angular.json,我认为这是尝试指定环境变量的问题的一部分。

【问题讨论】:

    标签: javascript angular angular6


    【解决方案1】:

    polyfill.ts中,添加这一行:

    (window as any).process = {
      env: { DEBUG: undefined },
    };
    

    参考:https://github.com/algolia/algoliasearch-client-javascript/issues/691


    npm i -S process,然后将此添加到polyfill.ts

    import * as process from 'process';
    window['process'] = process;
    

    【讨论】:

    • 为什么我的应用会随机需要这个?
    【解决方案2】:

    为了解决这个问题,我在 'polyfills.ts' 文件中添加了以下几行,

    (window as any).global = window;
    global.Buffer = global.Buffer || require('buffer').Buffer;
    global.process = require('process');
    

    【讨论】:

      【解决方案3】:

      这与 Angular v6 不兼容。浏览器中的 removed support (shim) 和 processglobal 变量。

      我建议你使用 Angular 5,直到 cosmic.js 修复错误。也许你甚至可以为它打开一个问题。

      【讨论】:

      • 感谢 Filipesilva 评论的链接。了解为什么存在这种不兼容性非常有用。事实是我们不应该使用变通方法来让“path”、“fs”或其他节点模块在浏览器中工作……我们不应该使用它们并在需要时使用 polyfill。
      【解决方案4】:

      这与 Angular 6 不兼容。他们在浏览器中删除了对进程和全局变量的支持(垫片)。

      在关闭 index.html 之前添加以下内容将消除错误。

      <script>
        var global = global || window;
        var Buffer = Buffer || [];
        var process = process || {
          env: { DEBUG: undefined },
          version: []
        };
      </script>
      

      【讨论】:

        【解决方案5】:

        只要您不满意将一些随机逻辑放入 polyfills.ts 并寻找在 Angular 应用程序中实际访问 process.env 的方法,请找到以下解决方案。

        angular.json 中将您的"builder": "@angular-devkit/build-angular:dev-server" 更改为"builder": "@angular-builders/custom-webpack:dev-server"

        【讨论】:

        • process 又被删除了吗?我已经为自定义 webpack 完成了此操作,但我仍然收到 process 错误
        • 好久没碰Angular了,忍不住:(
        【解决方案6】:
        <script>
            if (global === undefined || process === undefined) {
              var global = window;
              window['process'] = {
                env: { DEBUG: undefined },
              };
            }
        </script>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-22
          • 1970-01-01
          • 2022-10-23
          • 2015-05-05
          • 2011-05-11
          • 2017-02-07
          • 1970-01-01
          • 2019-05-26
          相关资源
          最近更新 更多