mrdulin / blog

Personal Blog - 博客 | 编程技术,软件,生活

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

在Angular6项目中使用graphql-tools的mockServer方法时报: Uncaught ReferenceError: process is not defined错误

mrdulin opened this issue · comments

问题

angular 6项目中使用graphql-toolsmockServer方法时报: Uncaught ReferenceError: process is not defined错误

下图在浏览器控制台打印出了错误的函数调用堆栈,错误发生在graphql模块中

image

环境及依赖版本

ng-cli:

image

package.json - dependencies

  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.0.3",
    "@angular/http": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    "core-js": "^2.5.4",
    "graphql": "^0.13.2",
    "graphql-tools": "^3.0.2",
    "rxjs": "^6.0.0",
    "zone.js": "^0.8.26"
  },

原因

angular 6开始,移除了processglobal这些变量在浏览器环境中的垫片(shim),也就是说,在浏览器环境中的window对象上,已经没有这些变量了。

先让我们回到angular 5时代在polyfills.ts模块中打印processglobal变量看看:

/***************************************************************************************************
 * Zone JS is required by default for Angular itself.
 */
import 'zone.js/dist/zone'; // Included with Angular CLI.

/***************************************************************************************************
 * APPLICATION IMPORTS
 */

console.log('process: ', process);
console.log('global: ', global);

image

同样的,在angular 6项目中的polyfills.ts模块中打印processglobal变量:

/***************************************************************************************************
 * Zone JS is required by default for Angular itself.
 */
import 'zone.js/dist/zone'; // Included with Angular CLI.

/***************************************************************************************************
 * APPLICATION IMPORTS
 */

console.log('process: ', process);
console.log('global: ', global);

image

可以看到process变量并不存在于window对象上,所以这个错误和使用不使用graphql-tools无关。

解决方案:

一、在polyfills.ts文件中加入以下代码:

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

二、通过webpack的DefinePlugin定义process.env变量

待更新...

参考链接

https://stackoverflow.com/questions/50313745/angular-6-process-is-not-defined-when-trying-to-serve-application/50313953?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

angular/angular-cli#9827 (comment)

angular/angular-cli#9827 (comment)