I can't use ES6 in webpack config file

2020-04-07 19:31发布

问题:

Is possible to use ES6 (especially import - instead of require) in webpack config file?

I have e.g.

import webpack from 'webpack';

but I am getting the following error

(function (exports, require, module, __filename, __dirname) 
{ import webpack from'webpack';

SyntaxError: Unexpected reserved word import

Folowing this thread I've named the config 'webpack.config.babel.js', I have babel(6.0.15), babel-core(6.1.2) installed as dev deps, but nothing works. Trying on WinXP.

Thanks for any help.

回答1:

You could use gulp and babel/register like this:

var gulp = require('gulp');
var webpack = require('webpack');
var gutil = require('gutil');
var babel = require('babel/register');
var config = require(path.join('../..', 'webpack.config.es6.js'));

gulp.task('webpack-es6-test', function(done){
   webpack(config).run(onBuild(done));
});

function onBuild(done) {
    return function(err, stats) {
        if (err) {
            gutil.log('Error', err);
            if (done) {
                done();
            }
        } else {
            Object.keys(stats.compilation.assets).forEach(function(key) {
                gutil.log('Webpack: output ', gutil.colors.green(key));
            });
            gutil.log('Webpack: ', gutil.colors.blue('finished ', stats.compilation.name));
            if (done) {
                done();
            }
        }
    }
}

...and your webpack config can have any es6. Tested and works for me.



回答2:

Rabet,

Do you have a link to a repo of your code? Could be very helpful for debugging if you could link us. It sounds like you may be missing the babel-loader package.

I've written a tutorial on getting webpack configured in ES6 (for react).

Below is some of the snippets that may be relevant to you.

import path from 'path'
export default {
  entry:['./js/app.js',
  ],

  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, 'build'),
    publicPath: 'http://localhost:8080/',
  },

  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loaders: ['react-hot', 'babel'],
    }],
  },

}

and my package.json file

{
 “name”: “Todo_tutorial”,
 “version”: “1.0.0”,
 “description”: “”,
 “main”: “index.js”,
 “scripts”: {
 “test”: “echo \”Error: no test specified\” && exit 1",
 “build”: “webpack --colors --progress”,
 “start”: “webpack-dev-server --hot --inline --color --progress ”
 },
 “author”: “”,
 “license”: “ISC”,
 “dependencies”: {
 “react”: “^0.14.0”
 },
 “devDependencies”: {
 “babel-core”: “^5.8.25”,
 “babel-loader”: “^5.3.2”,
 “flux”: “^2.1.1”,
 “webpack”: “^1.12.2”,
 “webpack-dev-server”: “^1.12.0”
 }
}

Source: https://medium.com/@ColeMurray/react-flux-in-es6-pt-1-2-e2a7b4aa074e