升级到Angular 8后,d3.js出现错误

6
我已将我的Angular 4应用程序更新到Angular 8。在开发构建中,应用程序运行正常,但在生产构建中却出现问题。当加载应用程序时,我收到以下错误信息:

Uncaught TypeError: Cannot read property 'document' of undefined at d3.js:8 at Object../node_modules/d3/d3.js (d3.js:9554) at webpack_require (bootstrap:78) at Module../src/app/pages/home/dashboard/map/map.component.ts (main-es2015.js:9841) at webpack_require (bootstrap:78) at Module../src/app/pages/home/home.routes.ts (home.routes.ts:2) at webpack_require (bootstrap:78) at Module../src/app/pages/home/home.module.ts (home.event.bus.ts:5) at webpack_require (bootstrap:78)

我的tsconfig.json文件如下所示。
{
  "compileOnSave": false,
  "compilerOptions": {
  "importHelpers": true,
  "outDir": "./dist/out-tsc",
  "baseUrl": "src",
  "sourceMap": true,
  "declaration": false,
  "moduleResolution": "node",
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "target": "es2015",
  "typeRoots": [
    "node_modules/@types"
  ],
  "lib": [
    "es2016",
    "dom"
  ],
  "module": "esnext",
  "paths": {
    "core-js/es7/reflect": ["../node_modules/core-js/proposals/reflect- 
     metadata"],
    "core-js/es6/*": ["../node_modules/core-js/es/*"]
  }
 }
}

我尝试将目标从 es2015 改为 es5,但没有成功,并在 vendor.js 中出现错误。需要帮助,谢谢。

2个回答

6

我通过将 tsconfig.json 文件中的目标从 es2015 更改为 es5,解决了该问题。d3库目前与es2015不兼容。

这会导致d3.js中使用UTF-8符号(如π)而引发错误。为了解决这个问题,您可以在HTML主机文档上指定UTF-8字符集。

<meta http-equiv="content-type" content="text/html; charset=UTF8">

3
我不认为那是问题所在。在Angular 7中,可以选择针对es2016/es2017进行编译,这显然与d3兼容。现在升级到Angular 8后,这种方法已经不再可行。这可能意味着,在Angular 7中未将d3包含在编译中,但在v8中已经包括,或者Angular 8存在某些问题。 - Marc J. Schmidt

0

Angular 8决定在目标为es2015+时将type="module"放入index.html中。在我的例子中,我成功地使用了带有Angular 7的es2017,当然还包括d3(通过plotly.js)。除了修改dist/index.html之外,我没有找到任何解决方案。对我来说,这是一个完美的解决方案,因为生成的代码可以正常工作。

要做同样的事情,首先安装https://www.npmjs.com/package/@angular-builders/custom-webpack,并按照他们的描述进行配置。创建extra-webpack.config.js后,将以下代码放入该文件中:

class FixIndex {
  constructor(path) {
    this.path = path;
  }

  done() {
    const path = __dirname + '/dist/' + this.path;
    if (!fs.existsSync(path)) {
        console.log('path not found', path);
        return;
    }
    let file = fs.readFileSync(path, 'utf8');
    file = file.replace(/type="module"/g, '');

    fs.writeFileSync(path, file);
  }

  apply(compiler) {
    compiler.hooks.done.tap(
        'FixIndex',
        () => {
            setTimeout(() => {
                this.done();
            }, 1);
        }
    );
  }
}

module.exports = {
  plugins: [
    new FixIndex('deepkit/index.html'),
  ],
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接