【问题标题】:Webpack with TypeScript - When targeting to ES6 the import keywork isn't define带有 TypeScript 的 Webpack - 以 ES6 为目标时,未定义导入键
【发布时间】:2017-04-13 14:05:04
【问题描述】:

我正在开发一个新的 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 导入语法。

【问题讨论】:

  • 因为 Webpack 目前不支持 ES6 导入/导出。 Webpack 2 仍处于 beta 版本。也许你can try to use it?
  • 确实 webpack1 不支持 ES6 模块,但这就是我使用 babel-loader 的原因。 Babel 需要将我的 ES6 导入/导出转换为 ES5 浏览器可以处理的东西。这有意义吗?

标签: typescript webpack ecmascript-6 babeljs ts-loader


【解决方案1】:

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

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

npm inpm install 的别名。-D--save-dav 的别名,这会将包添加到 package.json 文件中的 devDependencies 节点)

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']
                }
            },
            // ...
        ]
    }

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

【讨论】:

    猜你喜欢
    • 2017-02-25
    • 2015-12-07
    • 2017-06-29
    • 2016-06-24
    • 2017-11-13
    • 2017-02-02
    • 2016-05-23
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多