我正在尝试将 redux 集成到现有的 React 应用程序中。我的所有 React 代码都在 jsx 文件中。现在我介绍 redux 和 store.js。在编译 webpack 期间,store.js 上出现预期 token 错误
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 in ./project/static/public/js/store.js Module parse failed: /home/username/git/project/project/static/public/js/store.js Line 1:
Unexpected token You may need an appropriate loader to handle this file type. | import { applyMiddleware, createStore} from 'redux'; | import combineReducers from './reducers/index.js' | @ ./project/static/public/js/components/App.jsx 15:13-32
这些文件已经经历了多次迭代,试图解决并更好地理解 redux。我认为问题出在我的 webpack 配置上。
最佳答案
您使用的是哪个版本的 Babel?我猜你需要在 webpack 规则中使用 babel-loader 。此配置适用于 Babel 7 和 Webpack 4。
网页包规则:
{
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
最好!
关于javascript - 尝试将 redux 集成到 React 应用程序中。 Webpack 对 store.js 感到窒息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224571/