Search code examples
typescriptwebpackecmascript-6babeljsts-loader

Webpack with TypeScript - When targeting to ES6 the import keywork isn't define


I'm working on a new Angular2 project with Webpack as the model loader, and Typescript as the development language.

When I target the Typescript compiler to target to ES5 everything works fine. But When I target to ES6 and added babel-loader as the trasplier to ES5 I'm getting the error: Unexpected token import

Working ES5 configuration:

// 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')'

Not Working ES6 configuration:

// 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

I can't understand why the ES6 import keyword is not define???
I also notice that if I change the import statement to require() statement then I don't get the error, but I want to use the ES6 import syntax.


Solution

  • Finely I found the answer. When using babel-loader you will need not only install babel-loader and babel-core, but also babel-preset-es2015 module.

    1. Run shell/terminal commands:
    $ npm i babel-loader -D
    $ npm i babel-core -D
    $ npm i babel-preset-es2015 -D

    (npm i is alias for npm install. -D is alias for --save-dav which will add the packages to the devDependencies node in package.json file)

    2. Edit the webpack.config file:

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

    For more info, on how to config ts-loader with babel-loader see: https://gist.github.com/nojaf/daf886031072b572bc9a