简体   繁体   中英

Can't use ES6 import in webpack config

CommonJS import const webpack = require('webpack'); works fine, but ES6 import webpack from 'webpack'; no.

From Webpack Documentation :

Version 2 of webpack supports ES6 module syntax natively.

But it doesn't work out of the box for me.

I'm also tried:

  • use babel-loader for JS files;
  • add "babel" to the config files names.

But it's all doesn't work.

package.json

"scripts": {
    "build:dev": "webpack --config webpack.config.dev.babel"
},
"devDependencies": {
    "babel-loader": "^7.1.4",
    "webpack": "^4.8.3",
    "webpack-cli": "^2.1.3",
    "webpack-merge": "^4.1.2"
}

webpack.config.common.babel.js

export const /* in this implied like default */ module = {
    loaders: [
        {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: '/node_modules/'
        }
    ],
};

webpack.config.dev.babel.js

import webpack from 'webpack';
import merge from 'webpack-merge';
import commonConfig from './webpack.config.common.babel';

export default merge(commonConfig, {
    mode: 'development',
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('development')
        })
    ]
});

.babelrc

{
    "presets": ["es2015"]
}

And when i type npm run build:dev it's throws:

import webpack from 'webpack';
^^^^^^

SyntaxError: Unexpected token import

Questions:

  1. How to make ES6 import work?
  2. It is possible out of the box, ie without any babel-loader packages?

Well, the first thing I notice is that you can't use "import" in your webpack file. You need "require":

  const webpack = require('webpack');

You cannot use import because that is ES6, and how can you use ES6 if you haven't installed babel yet? No JS engine (afaik) natively supports ES6, and definitely not Node.

Also, I think you're going to get a warning for the ES2015 - I think it should be "babel-preset-env" now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM