Knows Not Much Knows Not Much - 5 years ago 177
Javascript Question

Use Babel with JavaScript

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.

Answer Source

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']
    }
 }

P.S. My first answer was wrong - /\.jsx?$/ also handle files with .js extensions

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download