尝试将redux集成到反应应用程序中 . Webpack在store.js上窒息

我正在尝试将redux集成到现有的反应应用程序中 . 我的所有反应代码都在jsx文件中 . 现在我介绍redux和store.js . 在编译webpack错误期间,store.js上出现了一个令人沮丧的令牌错误

webpack.config.js

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

var BUILD_DIR = path.resolve(__dirname, 'project/static/public/js');
var APP_DIR = path.resolve(__dirname, 'project/static/public/js/components');


module.exports = {
  entry: APP_DIR + '/App.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  resolve: {
    alias: {
      'react': path.join(__dirname, 'node_modules', 'react')
    }
  },
  module : {
    loaders : [
      {
        test : /\.jsx/,
        include : APP_DIR,
        loader : 'babel',
        presets : ['es2015']
      },
      {
        test : /\.js/,
        include : BUILD_DIR,
        exclude : /bundle.js||bundle.js.map||node_modules/,
        loader : 'babel',
        presets : ['es2015']
      }
    ]
  },
  watchOptions: {
    poll: true
  }

};

.babelrc

{
  "presets": [
    "es2015",
    "react"
  ],
  "env": {
    "start": {
      "presets": [
        "react-hmre"
      ]
    }
  },
  "plugins": [
      ["transform-es2015-arrow-functions", { "spec": true }],
      ["transform-class-properties"]
    ]
}

store.js

import { applyMiddleware, createStore} from 'redux';
import combineReducers from './reducers/index.js'


export default createStore(combineReducers)

error message

.project/static/public/js/store.js中的错误 . 模块解析失败:/home/username/git/project/project/static/public/js/store.js第1行:意外的令牌您可能需要一个合适的令牌加载器来处理这种文件类型 . |从'redux'导入{applyMiddleware,createStore}; |从'./reducers/index.js'中导入combineReducers @ ./project/static/public/js/components/App.jsx 15:13-32

这些文件在尝试解决并更好地理解redux时经历了多次迭代 . 我认为问题在于我的webpack配置 .

回答(1)

2 years ago

您使用的是哪个版本的Babel?我想你需要在webpack规则中使用babel-loader . 这个配置与Babel 7和Webpack 4一起罚款 .

WEBPACK规则:

{
        test: /\.js$/,
        include : BUILD_DIR,
        exclude : /bundle.js||bundle.js.map||node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },

和.babelrc文件示例:

{
  "presets": [[
    "@babel/preset-env", {
      "useBuiltIns": "entry"
    }],
    "@babel/preset-react"],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-export-default-from",
    "react-hot-loader/babel"
  ]
}

请记住,你需要安装babel-loader至少版本8.0.0,babel core 7.0.0和webpack 4.23 .

但是,我很确定问题是你需要在webpack中使用babel-loader插件 . 访问https://github.com/babel/babel-loader

最好!