Fez Vrasta
Fez Vrasta

Reputation: 14825

Cannot load ES6 module with Webpack

I have created a simple ES6 react-component module:

https://github.com/FezVrasta/react-resize-aware/blob/master/index.js

But when I try to load it with import ResizeAware from 'react-resize-aware' I get:

./~/react-resize-aware/index.js
Module parse failed: /Users/fez/Projects/test/node_modules/react-resize-aware/index.js Unexpected token (69:6)
You may need an appropriate loader to handle this file type.

What am I doing wrong here? The same module works perfectly if I save it inside my project folder. It just doesn't work when I load it from node_modules.

It gives error at:

return (
  <div {...this.props} style={rootStyle}>

This is my webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['react-hot', 'babel?presets[]=es2015'],
        include: path.join(__dirname, 'src')
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      },
      {
        test: /\.styl$/,
        loaders: [
          'style?sourceMap',
          'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
          'stylus'
        ]
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]
      },
      {
        test: /\.(eot|woff|woff2|ttf)$/,
        loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      }
    ]
  }
};

Upvotes: 0

Views: 320

Answers (1)

Christiaan
Christiaan

Reputation: 848

You have configured webpack to compile react code like this

{
    test: /\.js$/,
    loaders: ['react-hot', 'babel?presets[]=es2015'],
    include: path.join(__dirname, 'src')
},

You have specified the include to only your src directory in your project. This is a good practice as you do not want to transpile all your node_modules.

Nodejs probably understands most of the new ES6 syntax except for that ... operator.

If you want to distribute your code as a node module make sure you distribute the tranpiled version. See the prepublish npm script on how to automate this.

Upvotes: 1

Related Questions