导入语法不适用于 webpack

IT技术 javascript reactjs webpack
2021-05-14 12:28:40

我有Illegal import declaration错误。当我尝试将 react js repo 与 webpack 集成时

我从https://github.com/dptoot/react-event-calendar/blob/master/example/src/example.js迁移了原始源代码

我怎么能修复Illegal import declaration错误?

我认为该import语法仅适用于某些 js lib 吗?

错误

ERROR in ./app/main.js
Module build failed: Error: Parse Error: Line 2: Illegal import declaration
    at throwError (/Users/poc/sandbox/ha/node_modules/jsx-loader/node_modules/jstransform/node_modules/esprima-fb/esprima.js:2823:21)

主文件

var React = require('react');
const EventCalendar = require('react-event-calendar');

import moment from 'moment';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Button from 'react-bootstrap/lib/Button';
import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar';
import Popover from 'react-bootstrap/lib/PopOver';
import Overlay from 'react-bootstrap/lib/Overlay';

webpack.config.js

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


var config = module.exports = {
  // the base path which will be used to resolve entry points
  context: __dirname,
  // the main entry point for our application's frontend JS
  entry: './app/main.js',
  output: {
    filename: 'main.js'
  },

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

  module: {
    loaders: [
         {
          test: /\.jsx?$/, 
          exclude: /node_modules/, 
          loader: 'jsx-loader?insertPragma=React.DOM&harmony' }
    ]
  }

};
2个回答

使用 Babel viababel-loader转换import声明(如果需要,还可以使用其他 ES2015)。http://babeljs.io/docs/setup/#webpack

正如@JMM 回答的那样,您似乎需要babel-loader. 另外,我仍然面临同样的问题,最后通过编辑 webpack.config.js 之类的来解决

   module: {
     loaders: [
-      {test: /\.jsx?$/, loader: 'babel-loader'},
-      {test: /\.jsx$/, loader: 'jsx-loader'}
+      {test: /\.jsx$/, loader: 'jsx-loader'},
+      {test: /\.jsx?$/, loader: 'babel-loader'}
     ]
   },

或者因为jsx-loader看起来不再使用这个配置,它可以被删除。

我希望它会有所帮助