Search code examples
angularjsangulartypescriptbrowserifytsify

How do I solve ParseError: 'import' and 'export' may appear only with 'sourceType: module' when importing UpgradeAdapter?


I am trying to upgrade an existing anguar.js app to angular 2, following https://angular.io/docs/ts/latest/guide/upgrade.html.

The app is already written with Typescript, and we are using browserify and tsify to compile and bundle the app.

After installing the angular 2 dependencies with npm, and trying to bootstrap the hybrid app, browserify gives me the following error:

/my-project/node_modules/@angular/upgrade/static.js:8
export { downgradeComponent } from './src/aot/downgrade_component';
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

The error only shows up after adding the following code:

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app.module';
import {UpgradeModule} from '@angular/upgrade/static';

platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
    const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
    upgrade.bootstrap(document.documentElement, ['sagaDesktopApp']);
});

This is my tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false,
        "suppressImplicitAnyIndexErrors": true
    }
}

Any help would be very much appreciated.


Solution

  • I've reproduced the problem. It's related to the fact that there is a static.js file in @angular/upgrade and when Browserify attempts to resolve @angular/upgrade/static it resolves to:

    node_modules/@angular/upgrade/static.js
    

    However, the intention is for it to resolve to:

    node_modules/@angular/upgrade/static/package.json
    

    The package.json in the static directory contains a main entry that's used by non-ES6 bundlers like Browserify.

    Browserify mimics Node's module resolution mechanism and it's supposed to check for the file before the directory, so to fix the problem, append a trailing slash to the import:

    import { UpgradeModule } from '@angular/upgrade/static/';
    

    Browserify will then check the directory first and will resolve the package.json to the bundle.

    If you are interested, there is more information on the package.json file's main/module thing in this Tsify issue.