Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed.

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)

In addition, here is a snippet from my tsconfig.json file.

{
  "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/*"]
  }
 }
}

I attempted to change the target from es2015 to es5 without success, as it resulted in an error in vendor.js. Any assistance on resolving this issue would be highly appreciated. Thank you

Answer №1

To resolve the issue, I made a simple modification in the tsconfig.json file by changing the target from es2015 to es5. The d3 library currently does not support es2015.

This adjustment prevented an error in d3.js related to the usage of UTF-8 characters like π. To address this, you can set the charset to UTF-8 in the HTML host document.

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

Answer №2

Angular 8 made a change by including type="module" in the index.html when targeting es2015+. In my experience, I successfully used es2017 with Angular 7 while also incorporating d3 (via plotly.js). To address this change, I had to manually modify the dist/index.html file. This solution worked perfectly for me as it allowed the generated code to function without any issues.

To achieve the same result, start by installing https://www.npmjs.com/package/@angular-builders/custom-webpack and follow their configuration instructions. After creating the extra-webpack.config.js file, add the following code:

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'),
  ],
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is my Angular 2 app (TypeScript) not functioning properly?

My current project includes a component called EventListComponent import { Component } from 'angular2/core'; @Component ({ selector: 'el-events', templateUrl: 'app/events/event-list.component.html' }) export class E ...

Guide to assigning object values according to properties/keys

I'm currently diving into Typescript and exploring how to dynamically set object types based on specific keys (using template literals). Check out the code snippet below: interface Circle { radius: number; } interface Square { length: number; } ...

Utilize SCSS values within TypeScript by applying them on a class level

let changeClassDisplay = document.getElementsByClassName('sidebar'); for (var i = 0; i < changeClassDisplay.length; i += 1) { changeClassDisplay[i].style.display = 'block'; } I encountered an issue with this code whe ...

How to access the Parent ViewContainerRef within a projected child component in Angular 5

I have a unique application structure where the App component contains dynamically created components. The Parent component utilizes an <ng-content> element for projecting child components inside itself. App Component: @Component({ selector: &apo ...

Updating Values in Nested Forms with Angular Reactive Form

I have been grappling with a form setup that looks something like this: itemEntities: [ {customisable: [{food: {..}, quantity: 1}, {food: {..}, quantity: 5}]}, {customisable: [{food: {..}, quantity: 0}]}, ] My challenge lies in trying to u ...

The module 'DynamicTestModule' has imported an unexpected directive called 'InformationComponent'. To resolve this issue, please include a @NgModule annotation

Even though I found a similar solution on Stackoverflow, it didn't resolve my issue. So, let me explain my scenario. When running the ng test command, I encountered the following error: Failed: Unexpected directive 'InformationComponent' i ...

Struggling to locate the module with the imports of { async, TestBed } from '@angular/core/testing' and { IonicModule } from 'ionic-angular'

Unable to locate module: import { async, TestBed } from '@angular/core/testing'; import { IonicModule } from 'ionic-angular'; Working with Ionic 3, attempting to perform Unit testing on my application but encountering issues in the s ...

Tips for populating array values in an Angular9 template using forms

.html page <pre> <div *ngFor="let data of data;let i=index" class="row_wrap"> <div class="row_inner_wrap"> <div class="row"> <div class="col-md-12"> <div class="col-md- ...

Issues with loading Angular 4 Bootstrap JS post compiling

Utilizing normal bootstrap 3 within an Angular 4 application has been working well when compiling for development using ng serve. However, upon building the application with ng build, I encounter an issue where my bootstrap.js fails to load. Below are th ...

Is there a way to prevent the Drop event in Angular2?

In my Angular2 application, I have created a directive for an input field. To prevent paste or Ctrl+V within the host element of this directive, I used the following code which is functioning flawlessly: @HostListener('paste', ['$event&apos ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

I am facing difficulties in retrieving data from MongoDB using Angular 8

Having trouble loading data from MongoDB using Angular 8? I've successfully loaded data with https://jsonplaceholder.typicode.com/, but when trying locally at 'http://localhost:3000/employees', it doesn't work. I can post data but una ...

Mastering the TypeScript syntax for executing the MongoDB find method

Having trouble properly typing the find method of MongoDB in my TypeScript project that involves MongoDB. Here's the snippet I'm working on: import { ReitsType } from '@/app/api/types/reits'; import { NextRequest, NextResponse } from &a ...

The NestJS Backend is always being asked by Grafana to access the /api/live/ws endpoint

After successfully setting up Grafana and Grafana Loki with my NestJS Backend, everything seemed to be working fine. However, I started getting a 404 error from my NestJS because Grafana was requesting the /api/live/ws route. Is there a way to disable thi ...

Angular UI validation malfunctioning upon loading of the page

My webpage contains multiple rows with specific validation requirements - at least one Key, Time, and Input must be selected. Initially, the validation works as expected. However, after saving and reloading the page, the default selection for Key, Time, an ...

I would like to customize the Primeng switch by changing the values from boolean to 'N' or 'Y'

I integrated the primeNg p-switch component into my Angular 2 project. By default, the input switch's values are boolean. However, I would like to have the values set to 'N' or 'Y' instead of true or false. @export class MyCompone ...

Exploring the power of RxJs through chaining observers

In my Angular application, I am utilizing Observables to set up a WebSocket service. Currently, I have the following implementation: readwrite(commands: command[]) : Observable<response[]>{ const observable = new Observable((observer)=>{ ...

The process of extracting a value from an array of objects encountered an error due to the undefined object

I am looking to extract the value from an array within an object while also implementing error checking. The code I currently have checks if a specific key exists in the object and if the value associated with that key is of type array. If both condition ...

Guide to incorporating Jquery-Comment into Angular versions 2 and beyond

I've incorporated the Jquery-Comment plugin into my Angular 2 project by adding the necessary script and css files to my Index.html page. However, when initializing the Comment TextBox id within a script tag, I encountered an error in the console. ...

Update your AngularJS to the most recent version of Angular

We are faced with the task of upgrading a legacy MVC website that currently utilizes AngularJs to the latest version of Angular. Surprisingly, our current website only scratches the surface of what Angular has to offer - mainly using it for databinding and ...