Babel 输出 Angular2 文件的精确副本

Babel Outputting Exact Copy of Angular2 File

我正在尝试使用 Babel CLI 将带有 Angular 2(因此它具有 @ 装饰器)的 ES2015 js 编译成 ES5,以便它可以被网络浏览器使用,但它只是创建了一个精确的副本文件(仍然使用@符号以及导入关键字)。

我从终端使用 npm run build 使 babel 创建 boot.js 文件的 ES5 版本。 Babel 在我的 package.json 文件中配置如下:

{
    "name": "angular2-quickstart",
    "version": "1.0.0",
    "babel": {
        "plugins": [
            "syntax-decorators"
        ]
    },
    "scripts": {
        "start": "npm run lite",
        "lite": "lite-server",
        "build": "babel boot.js -d lib"
    },
    "license": "ISC",
    "dependencies": {
        "angular2": "2.0.0-beta.0",
        "systemjs": "0.19.6",
        "es6-promise": "^3.0.2",
        "es6-shim": "^0.33.3",
        "reflect-metadata": "0.1.2",
        "rxjs": "5.0.0-beta.0",
        "zone.js": "0.5.10"
    },
    "devDependencies": {
        "babel-cli": "^6.3.17",
        "lite-server": "^1.3.1"
    }
}

这是我试图编译成 ES5 的实际 JS 文件:

'use strict';
import {Component, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'my-app',
  template: '<h1>Hello {{ name }}</h1>'
})
// Component controller
class MyApp {
  constructor() {
    this.name = 'Max';
  }
}

bootstrap(MyApp)

这是浏览器控制台中的错误:

Uncaught SyntaxError: Unexpected token import
boot.js:2 Uncaught SyntaxError: Unexpected token import

我正在使用 visual studio 代码作为我的 IDE。这是我的 jsconfig.json 文件来配置 visual studio 代码:

{
    "compilerOptions": {
        "target": "ES6",
        "module": "commonjs",
        "experimentalDecorators": true
    }
}

我后来意识到我的代码是打字稿,而不是 ES6 javascript。这很可能是问题所在。

不幸的是,babel 6 仍然存在一些问题,例如当找不到插件时静默失败。

安装以下插件:

  • babel-plugin-syntax-decorators
  • babel-plugin-transform-decorators

在选项中也包含 transform-decorators 插件:

"plugins": [
    "syntax-decorators",
    "transform-decorators"
]

您很可能还需要一个模块变压器


但如果您的代码最终是 TypeScript,那么所有这些都是多余的。