Angular 6 - 尝试为应用程序提供服务时未定义流程

问题描述 投票:0回答:8

当我尝试使用 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 属性未定义有关。

我正在关注本教程这里

我的确切代码可以在这里找到

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

javascript angular angular6
8个回答
76
投票

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;

30
投票

为了解决该问题,我将以下行添加到“polyfills.ts”文件中,

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

10
投票

这与 Angular v6 不兼容。他们删除了浏览器中对process

global
变量的支持
(垫片)。

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


9
投票

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

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

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

3
投票

只要您不满意在

polyfills.ts
中放入一些随机逻辑并寻找一种方法来实际访问 Angular 应用程序中的
process.env
,请找到以下解决方案。

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


0
投票

我在 Angular 14 应用程序中“突然”遇到了同样的问题。

原来是我自己引入的:我忘记在服务类中删除对

inspect
(来自 Nodes
util
包)的调用。删除对
inspect
的呼叫对我来说很有效。

我在调试 Jasmine 单元测试时添加了对

inspect
的调用。在 Jasmine 中运行单元测试会执行 Node 中的代码。这就是它在那种环境中起作用的原因。

inspect
中有一条线

   if ( process.env.DEBUG )

由于

process
未在浏览器中全局定义,因此当作为 Angular 应用程序运行时,此行的执行会失败。

此类错误不仅限于

util.inspect
,而是在浏览器中运行并内部访问的 Node 的任何核心模块中都会发生
process.env

由于核心模块的内部实现可能因 Node 版本而异,因此使用 Node 中的核心模块会给您的应用程序带来风险,即在进行部署构建的计算机上更新 Node 可能会破坏您的应用程序。

“路径”是我想到的另一个候选者。


0
投票

如果您需要通过服务部署 Angular 6:

polyfills.ts:

(window as any).global = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
(window as any).process = {
    env: { DEBUG: undefined },
    version: '', // to avoid undefined.slice error
};

-1
投票
<script>
    if (global === undefined || process === undefined) {
      var global = window;
      window['process'] = {
        env: { DEBUG: undefined },
      };
    }
</script>
© www.soinside.com 2019 - 2024. All rights reserved.