Use Babel with JavaScript

2019-07-08 12:55发布

问题:

I am trying to write my first babel program and kind of stuck.

I wrote script 1

var message = "Hello World";
module.exports = message;

and script2

var message = require('./script1');
document.write(`This is formatted with ES6 ${message}`);

my webpack.config.js looks like

module.exports = {
    entry: {
         main: [
            './script1.js',
            './script2.js'
        ]
    },
    output: {
        filename: "./public/[name].js"
    },
    loaders: {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel'
    }
}

The above code works and I am able to see the output but now if I modify script2 to

import message from './script1';
document.write(`This is formatted with ES6 ${message}`);

then when I run webpack it says

ERROR in ./script2.js
Module parse failed: /Users/a.c/MyProjects/ReactTutorial/script2.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import message from './script1';
| document.write(`This is formatted with ES6 ${message}`);
 @ multi main

My understanding is that because I am using babel, I should be able to use the new ES6 way of importing stuff into my code easily.

回答1:

Most likely you have forgotten to specify es2015 preset for babel.

  1. Make sure it's installed:

    > npm i -D babel-preset-es2015
    
  2. You have two options to specify this preset for babel.

    1. Create .babelrc file and specify the preset there:

      {
          "presets": ["es2015"]
      }
      
    2. Specify the preset using query property:

      module: {
        loaders: [
          {
            test: /\.jsx?$/,
            include: /src/,
            loader: 'babel',
            query: {
              presets: ['es2015']
            }
          }
        ]
      }
      


回答2:

Try add resolve.extensions to config file (in order to avoid always write extensions when you import .js or .jsx files) also if you are using babel 6 you need install couple packages babel-preset-es2015 and babel-preset-react

module.exports = {
    entry: {
         main: [
            './script1.js',
            './script2.js'
        ]
    },

    output: {
        filename: "./public/[name].js"
    },

    loaders: {
        test: /\.jsx?$/, // or /\.(js|jsx)$/
        exclude: /node_modules/,
        loader: 'babel',
        query: {
           presets: ['es2015', 'react']
        }
    },

    resolve: {
        extensions: ['', '.js', '.jsx']
    }
 }