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

Sizing the Angular CDK overlay backdrop appropriately when connecting it to a component

Is there a way to have a CDK overlay specifically cover a certain component using flexibleConnectedTo()? I am struggling with ensuring that the overlay backdrop only covers the targeted component, rather than the entire page. The CSS for the cdk-overlay-co ...

Troubleshooting problem with ion-input in Ionic 3 regarding the keyboard issue

Issue with Keyboard Overlaying Button In my ionic3 app, I am facing an issue where the keyboard overlaps the "Registrarse" button when it is open, as shown in the image. The button is positioned at the bottom of the ion-content using CSS rules such as pos ...

Initial values of dual knob settings on Ionic Range and their ability to update dynamically

As someone new to using Ionic and TypeScript, I am facing challenges in setting initial values for my Ionic Range component (V5). Referring to other posts, it seems that there are upper and lower properties within ngModel, but I'm unsure about the bes ...

Event when a panel menu in PrimeNG is clicked

<p-panelMenu [model]="items" [style]="{'width':'300px'}" (click)="clicked($event)"></p-panelMenu>`<p-dialog header="Title" [(visible)]="display"> page 1 ` this is my ts ` click: any; display: boolean = false; ...

Using type values in TypeScript

I am trying to assign interfaces as values within a config object: export interface RouterConfig { startEvents?: typeof RouterEvent[]; completeEvents?: typeof RouterEvent[]; } The intended usage is as follows: private config: RouterConfig = { star ...

Execute the 'loadURL' function in the electron-Angular project when the Angular Compiler has finished preparing

When working with electron-Angular tutorials, it is common to create the window and load index.html from localhost after a set timeout. You'll often come across instructions similar to this: // set timeout to render the window not until the Angular c ...

Tips for distributing services in Angular

I'm currently working on an angular application that consists of different modules, with lazy loading enabled. In one of the modules, let's call it module A, I have a service called userService that I need to access in a component located in anot ...

Before running any unit tests, I have to address all linting issues as required by ng test

Upon running ng test, the output I receive is as follows: > ng test 24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/ 24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/ ...

Issue with directive implementation of regex test as attribute - validations in typescript and angular

I am currently working on a project to create a module with custom validation directives. These validations are implemented using regular expressions (regex). The specific error I encountered is: Error: [$injector:unpr] Unknown provider: REG_EXPProvid ...

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

Expanding the capabilities of generic functions in TypeScript using type variables

When working with generics in TypeScript, it is often beneficial for a function that accepts generically-typed arguments to have knowledge of the type. There exists a standard approach to achieve this using named functions: interface TestInterface<T> ...

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: I have attempted to fix this issu ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Retrieve error information from ResponseContentType.Blob request type

I am currently struggling with an issue related to making a request of type ResponseContentType.Blob and receiving an error message when the call fails. The code I am using is quite simple: let headers = new Headers({'Content-Type': 'appl ...

synchronize the exchange of information and events between two components

Just joined this platform and diving into Angular 7 coding, but already facing an issue. I've set up two components along with a service. The data is fetched by the service upon clicking a button in the searchbar component, and I aim to display it i ...

What is the reason for encountering a TypeScript error when using a union type?

interface Bird { age:string, eat:()=>any } interface Fish { age:string, swim:()=>any } type Pet = Fish | Bird; everything looks good so far, defining a Pet type const pet:Pet={ age:"sd", eat:()=>{} } when trying to return ...

Utilizing arrayUnion function in Firestore with Angular

My journey to learn Firestore has hit a roadblock. The documentation on AngularFire and FieldValue hasn't been much help. Every time I try to use FieldValue, it throws an error saying "FieldValue does not exist." const userRef = this.firestore.collect ...

Instructions for transferring an Angular / Node.js application to a different computer

Hey there! I'm in the process of transferring my project to a new computer. Just to let you know, I've already set up node.js and mongoDB on the new machine. When it comes to the Angular app, I understand that I need to copy over the frontEnd d ...

Determining if a component is nested within itself in Angular 6 is a crucial task

My goal is to develop a custom Angular component for a nested navigation menu with multiple levels. Below is an example of how the menu structure looks: app.component.html <nav-menu> <nav-menu-item>Section 1</nav-menu-item> <nav- ...

Angular - developing a custom web element to enhance the project

Is there a way to convert a single module into a web component and integrate it within the same project? Specifically, I have 3 modules in my project and I am looking to transform only module1 into a web component and incorporate it seamlessly. Thank you! ...