Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack getting started, import error

I'm getting started with Webpack, but already ran into the following problem: I created an app/index.js file (as specified in the documentation). I also created an index.html file (copied the HTML and CSS from the documentation). I ran the correct commands in the CLI (including generating a dist/bundle.js file).

The code:

<!DOCTYPE html>
<html lang="nl">
    <head>
        <meta charset="UTF-8">
        <title>Webpack</title>
        <!-- <script src="https://unpkg.com/[email protected]" type="text/javascript"></script> -->
        <script src="dist/bundle.js" type="text/javascript"></script>
    </head>
    <body>
        <!-- Markup here -->
        <div id="root"></div>

        <!-- <script src="app/index.js" type="text/javascript"></script> -->
    </body>
</html>

The JS:

// To bundle the lodash dependency with the index.js, we need to import lodash.
import _ from 'lodash';

function component () {
    var element = document.createElement( 'div' );

    /* lodash is required for the next line to work */
    element.innerHTML = _.map( [ 'Hello, webpack' ], function( item ) {
        return item + ' ';
    });

    return element;
}

document.body.appendChild( component() );

This returns the following console error: bundle.js:48 Uncaught SyntaxError: Unexpected token import

How do I get this to run correctly?

like image 868
erol_smsr Avatar asked Sep 10 '25 20:09

erol_smsr


1 Answers

As has been suggested, you'll need to setup up Babel to get this working.

Install babel dependancies:

    npm install --save-dev babel-loader babel-core babel-preset-react babel-preset-es2015

You'll need to edit your webpack.config.js file to include the babel loader settings:

var webpack = require('webpack');

module.exports = {
  ...
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};
like image 161
Pineda Avatar answered Sep 13 '25 09:09

Pineda