react-router引入Router時報錯
阿新 • • 發佈:2019-01-29
1. 檔案佈局
routes/index.js
import React from 'react';
import { Router, Route, hashHistory } from 'react-router';
import Home from '../views/Home';
import Detail from '../views/Detail';
const routes = (
<Router history={hashHistory}>
<Route path="/" component={Home}/>
<Route path="/detail/:id" component={Detail}/>
</Router>
);
export default routes;
app.js
import ReactDOM from 'react-dom';
import routes from './routes';
ReactDOM.render(routes, document.getElementById('root'));
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'build' ),
filename: 'app.bundle.js',
publicPath: '/build',
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
}]
}
}
package.json
{
"scripts": {
"build": "webpack"
},
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader" : "^7.1.2",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-redux": "^5.0.2",
"react-router": "^3.0.2",
"redux": "^3.6.0",
"redux-logger": "^2.8.1",
"redux-thunk": "^2.2.0",
"react-router-redux": "^4.0.8",
"whatwg-fetch": "^2.0.3"
},
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^3.10.0"
}
}
2. 錯誤展示
當執行npm run build時報出如下錯誤
3.錯誤分析
- 剛開始是因為react-route載入的是V4版本的,報這樣的錯很正常,但當安裝V3版本時依舊報這樣的錯,查了很久才知道是因為:routes/index.js寫的是es2015的語法,但卻沒有加ES2015的babel preset,也沒有加react的preset。
4.解決方案
在webpack.config.js中的
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
}]
}
修改為
module: {
rules: [{
test: /\.js$/,
loader: ['babel-loader?presets[]=react&presets[]=es2015'],
exclude: /node_modules/,
}]
}
然後運用npm install --save-dev babel-preset-react babel-preset-es2015
再安裝一下preset就可以解決了,再次執行npm run build
時正常顯示為
> @ build E:\self\redux-blog
> webpack
Hash: e4c4a9ef55a286df216f
Version: webpack 3.10.0
Time: 2034ms
Asset Size Chunks Chunk Names
app.bundle.js 908 kB 0 [emitted] [big] main
[115] ./src/app.js 416 bytes {0} [built]
[215] ./src/routes/index.js 866 bytes {0} [built]
[243] ./src/views/Home.js 3.24 kB {0} [built]
[244] ./src/views/Detail.js 3.26 kB {0} [built]
+ 241 hidden modules