【发布时间】:2019-07-14 03:13:02
【问题描述】:
我正在使用 webpack-dev-server 进行开发并同样响应路由器。这是我的 wepack 配置。
const webpack = require('webpack');
const path = require('path');
const common = require('./common.config.js')
const merge = require('webpack-merge')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = merge(common, {
devtool: 'source-map',
mode:'development',
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
{
// Adds CSS to the DOM by injecting a `<style>` tag
loader: 'style-loader'
},
{
// Interprets `@import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
},
{
// Loader for webpack to process CSS with PostCSS
loader: 'postcss-loader',
options: {
plugins: function () {
return [
require('autoprefixer')
];
}
}
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'sass-loader'
}
]
}
]
},
devServer:{
contentBase: path.join(__dirname, '../dist'),
port: 3000,
proxy:{
'/api': 'http://127.0.0.1:5000',
},
historyApiFallback:true,
overlay: true,
stats: 'normal'
},
watchOptions: {
ignored: /node_modules/
},
plugins: [
new CleanWebpackPlugin(['../dist'], { exclude:['sw.js']}),
new HtmlWebpackPlugin({
title: 'Script App - Dev',
filename: '../dist/index.html',
template:'index_template.html'
}),
new MiniCssExtractPlugin({
filename: 'bundled_styles.css'
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
});
这是我的应用程序的入口点(我已经定义了路线)
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import {BrowserRouter, Route, Switch} from 'react-router-dom'
import configureStore from './store/configureStore';
import FirstComponent from './FirstComponent';
import SecondComponent from './SecondComponent';
import App from './App';
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<App>
<Switch>
<Route path="/first/:a_code" component={FirstComponent} />
<Route path="/second" component={SecondComponent} />
</Switch>
</App>
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
我正在使用 react-router v4 和 wepack v4.29。
我的问题:当我使用 history 属性从我的代码中推送路由时,一切正常,但是当我用路由刷新浏览器时,一切都变为空白。 只有在具有多条路径的路由中才会出现这种行为(/first/:param)。
我尝试过的事情:我从一些 SO 帖子中读到,我必须将我的 webpack 配置中的 historyApiFallback 属性设置为 true,我做到了,但它仍然没有帮助.
this github issue 中的一个 cmets 表示,如果 webpack 配置中提供了某些 proxy 配置,historyApiFallback 将无法正常工作。
我不想删除这些 proxy 配置,因为我正在对运行在不同端口上的另一台服务器进行 api 调用。
谁能帮我解决这个问题?请!
【问题讨论】:
-
您能否举例说明路线在地址栏中的外观?
-
@RRK 这里是一个路由示例:localhost:3000/first/rt
-
只是一个预感,你可以试试不带下划线的参数名吗?例如
:a_code到:acode -
@RRK 我怀疑这是否是问题所在,因为我之前使用了不带下划线的不同变量名,但它没有解决问题。
标签: reactjs webpack react-router