Do I need to configure webpack for ES6?

2019-07-22 12:21发布

I have an angular app with a .tsconfig file targeting ES6.

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom",
      "es2018.promise"
    ]
  }
}

The following angular component (Typescript):

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { DispositifsDATIRoutingModule } from './dispositifsDATI.routes';
import { SharedModule } from '../shared/shared.module';
import { DISPOSITIFS_DATI_COMPONENTS } from './index';

import { InputUtilitiesModule } from 'ng-uikit-pro-standard';
import { MaterialChipsModule, BadgeModule, IconsModule, WavesModule } from 'ng-uikit-pro-standard';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    SharedModule,
    HttpClientModule,
    DispositifsDATIRoutingModule,
    InputUtilitiesModule,
    MaterialChipsModule,
    BadgeModule,
    IconsModule,
    WavesModule
  ],

  declarations: [DISPOSITIFS_DATI_COMPONENTS]
})

export class DispositifsDATIModule { }

is transpiled by webpack to:

/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DispositifsDATIModule", function() { return DispositifsDATIModule; });

Which fails at runtime with:

ReferenceError: Cannot access 'DispositifsDATIModule' before initialization

I have no idea what is going on here.

Is there something to change in the webpack config around the use of ES6?


EDIT: This seems to be an issue in angular and/ or TypeScript regarding ES2015

2条回答
我命由我不由天
2楼-- · 2019-07-22 12:47

I guess you have circular dependencies here, your component file (let's say it is MyComponent.ts) imports DISPOSITIFS_DATI_COMPONENTS from the ./index.ts while index.ts imports the component from the ./MyComponent.ts.

So they depend on each other. In that case, DISPOSITIFS_DATI_COMPONENTS can be not initialized by the time you use it.

I would extract it to a third file in order to avoid circular dependencies

UPD: here is an useful article https://blog.angularindepth.com/how-to-break-a-cyclic-dependency-between-es6-modules-fd8ede198596

查看更多
倾城 Initia
3楼-- · 2019-07-22 12:50

All right, this error was caused because I was referencing a module that was using TypeScript decorators. I removed the decorators in favor of the equivalent API and the problem is gone.

查看更多
登录 后发表回答