简体   繁体   中英

Can not import module: You may need an appropriate loader

I have a React project using bower and webpack .

I am trying to use this module https://github.com/jrowny/react-absolute-grid .

I installed it with npm and I added it to my code like this:

import AbsoluteGrid from 'react-absolute-grid/lib/AbsoluteGrid.jsx';

When importing the module, I get this issue:

Line 3: Unexpected token
You may need an appropriate loader to handle this file type.
| 'use strict';
|
| import React from 'react';

I suspect the problem is that within webpack.config.js I only load files from where my code is:

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

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
  entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  module : {
    loaders : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel'
      }
    ]
  }
}

module.exports = config;

However, I'm not sure.

I saw questions with a similar error message on SO but they had other issues as far as I could see.

Change the way you import the module:

From:

import AbsoluteGrid from 'react-absolute-grid/lib/AbsoluteGrid.jsx';

To:

import AbsoluteGrid from 'react-absolute-grid';

And you should better exclude node_modules and bower_components in webpack configs:

...
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/

Also, you should better use babel-loader with react and es2015 babel presets.

Install them:

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

And inclue in webpack configs:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM