Search code examples
typescriptangulargulpcommonjs

Can not run angular2 in commonjs way


First, I don't know the difference between @angular and angular2 in package.json. But I like angular2 way in package.json. Here is my github source.

The problem is that I can't change "system" to "commonjs" in tsconfig_c.json, otherwise angular2 will throw error that I can't understand.

HTML:

<!DOCTYPE html>
<html>
<!-- #docregion head -->
<!-- #docregion base-href -->

<head>
  <base href="/" />
  <!-- #enddocregion base-href -->
  <title>Angular 2 Seed</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <!-- #docregion css -->
  <link rel="stylesheet" href="styles.css">
  <!-- #enddocregion css -->

  <!-- 1. Load libraries -->
  <script src="libs/angular2-polyfills.js"></script>
  <script src="libs/system.src.js"></script>
  <script src="libs/Rx.js"></script>
  <script src="libs/angular2.dev.js"></script>
  <script src="libs/router.dev.js"></script>

  <!-- 2. Configure SystemJS -->
  <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/bootstrap')
            .then(null, console.error.bind(console));
    </script>
</head>
<!-- 3. Display the application -->

<body>
  <my-app>Loading...</my-app>
</body>

</html>

Config:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "node_modules"
  ]
}

If compile the "system" way, all is good. But I prefer the "commonjs" way. Anyone could help me fix this?


Solution

  • As said by @Sanket, the angular2 package is the old beta version of Angular 2. About your question, if you compile in commonjs, you must tell SystemJs that your app is in commonjs, so you have to change in index.html the configuration:

      System.config({
        packages: {        
          app: {
            format: 'cjs', // commonjs
            defaultExtension: 'js'
          }
        }
      });