2

我正在开发一个新的 Angular2 项目,其中 Webpack 作为模型加载器,Typescript 作为开发语言。

当我将 Typescript 编译器定位到 ES5 时,一切正常。但是当我以 ES6 为目标并将其添加babel-loader为 ES5 的 trasplier 时,我得到了错误:Unexpected token import

工作 ES5 配置:

// tsconfig.json
"compilerOptions":
{
    "target": "es5",
    // ..
}

// webpack.config.js   
module:
    {
        loaders:
        [
            { test: /\.tsx?$/, exclude: /node_modules/, loader: "ts-loader" },
            { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
            // ...
        ]
    }

// app.ts
import 'core-js' // this line is transpiled by ts-comiler/loader to 'require('core-js')'

不工作的 ES6 配置:

// tsconfig.json
"compilerOptions":
{
    "target": "es6",
    // ..
}

// webpack.config.js   
module:
    {
        loaders:
        [
            { test: /\.tsx?$/, exclude: /node_modules/, loader: "babel-loader!ts-loader" },
            { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
            // ...
        ]
    }

// app.ts
import 'core-js' // this line throw the error: Uncaught SyntaxError: Unexpected token import

我不明白为什么没有定义 ES6 的 import 关键字???
我还注意到,如果我将 import 语句更改为 require() 语句,则不会出现错误,但我想使用 ES6 导入语法。

4

1 回答 1

2

我很好地找到了答案。使用babel-loader时不仅需要安装babel-loaderand babel-core,还需要安装babel-preset-es2015模块。

1. 运行 shell/终端命令:(
$ npm i babel-loader -D
$ npm i babel-core -D
$ npm i babel-preset-es2015 -D

npm i.npm install-D别名,--save-dav它会将包添加到devDependenciespackage.json 文件中的节点)

2. 编辑 webpack.config 文件:

// webpack.config.js   
module:
    {
        loaders:
        [
            { 
                test: /\.tsx?$/, 
                exclude: /node_modules/, 
                loader: "babel-loader?presets[]=es2015!ts-loader" 
            },
            { 
                test: /\.js$/, 
                exclude: /node_modules/, 
                loader: "babel-loader",
                query:
                {
                    presets: ['es2015']
                }
            },
            // ...
        ]
    }

有关如何配置ts-loader的更多信息,babel-loader请参见:https ://gist.github.com/nojaf/daf886031072b572bc9a

于 2016-11-30T11:38:27.837 回答