【问题标题】:Compiling/Transpiling from Typescript to ES5 not working从 Typescript 编译/转译到 ES5 不起作用
【发布时间】:2017-02-08 17:43:53
【问题描述】:

我正在使用 Webpack 并尝试使用 angular2。

这就是为什么我编辑了我所有的东西以便能够编译打字稿。我的计划是像 here 那样做,所以将 typescript 编译为 ES6,然后使用 Babel 将其转译为 ES5。

这就是我的小应用的样子:

import {Component} from 'angular2/core';


@Component({
    selector: 'angular-2-component',
    template: '<h1>Hello World!</h1>'
})

export class angular2Component {
}

这就是我的 tsconfig.json 的样子:

{
  "compilerOptions": {
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "typeRoots": [
      "../node_modules/@types"
    ],
    "types" : []
  },
  "exclude": [
    "node_modules"
  ]
}

这就是 webpack 配置中的 loader 配置:

{
   test: /\.ts(x?)$/,
   loader: 'babel-loader!ts-loader'
}

我还尝试使用 compilerOptions,将目标设置为 es5,将模块设置为 es2015,等等……但它不起作用。我总是遇到同样的错误:Unexpected token import,指向 angular2Component-App 的第一行。所以它不知道导入。此外,在浏览器中,您可以看到只有 @Component 部分似乎被正确编译/转译,然后看起来像这样:

export let angular2Component = class angular2Component {};
    angular2Component = __decorate([Component({
        selector: 'angular-2-component',
        template: '<h1>Hello World!</h1>'
    }), __metadata('design:paramtypes', [])], angular2Component);

但是写在上面,还是有同一行import {Component} from 'angular2/core';,根本没有编译/转译。

有人知道问题是什么吗?

【问题讨论】:

    标签: typescript webpack ecmascript-6 babeljs es6-modules


    【解决方案1】:

    作者肯定已经不感兴趣了,但无论如何可能会有所帮助。

    TS + Webpack + React 也有同样的问题。

    添加一个简单的 .babelrc 文件,比如

       {
         "presets": [
            ["latest", { "es2015": { "loose": true } }]
         ],
         "env": {},
         "comments": true
      }
    

    解决了问题。

    【讨论】:

    • 你是否在 webpack 配置中引用了这个 .babelrc 文件?还是其他地方?
    • @waz 我不记得这样做了。通常 webpack 会自己找到.babelrc。但已经有一段时间了,可能是错误的。
    猜你喜欢
    • 2018-05-08
    • 2021-11-06
    • 1970-01-01
    • 2016-09-23
    • 2014-10-12
    • 2018-05-29
    • 1970-01-01
    • 2020-02-15
    • 2021-04-15
    相关资源
    最近更新 更多