1
votes

I've been using Angular2 With JSPM (v17), but the only way I've been able to get it to work is to configure typescript to compile my modules as commonjs. However, in doing so, I always see the following warning for each file:

TypeScript [Warning] transpiling to CommonJS, consider setting module: "system" in typescriptOptions to transpile directly to System.register format

When I set module to system I get the following runtime error:

TypeError: Cannot read property 'forRoot' of undefined

Which is being thrown from this bit of code:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
    { path: '', redirectTo: '/login', pathMatch: 'full' },
];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

If I remove my routing module from the project, I end up seeing the following error:

core_1.Component is not a function

Around my AppComponent:

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<h1>hello world</h1>`,
})
export class AppComponent { }

Apparently, any Angular imports are coming back as null.

Here's my tsconfig.json:

{
    "compilerOptions": {
        "target": "es2016",
        "module": "system",
        "moduleResolution": "node",
        "inlineSourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
            "es2016",
            "dom"
        ],
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true
    },
    "exclude": [
        "jspm_packages"
    ]
}

I've also tried overriding the format for all @angular packages to esm, but then I see the following runtime error:

Can't add property ng, object is not extensible

Is commonjs the only way to go or am I missing a setting?

1

1 Answers

2
votes

From Guy Bedford:

Yes this was a change in SystemJS 0.20 where named exports for non-ES modules are no longer supported, in order to align with how interop will work in NodeJS between ES modules and CommonJS, which is to only provide compatibility with the default import form - import module from 'module' (equivalent to import {default as module} from 'module').

To include CommonJS modules with named exports, I needed to add an override to each angular library, including any other third-party libraries that were commonjs.

"meta": {
  "*.js": {
    "esModule": true
  }
}

For now, it seems the best to just set typescript to use commonjs as the module system.