使用 webpack 构建应用程序后,React 路由不起作用
当我使用 webpack 服务器(npm start)运行应用程序时,路由工作正常
webpack.config 文件
var webpack = require('webpack');
module.exports = {
entry: {
'index': [
'webpack-dev-server/client?http://localhost:8080/',
'webpack/hot/only-dev-server',
'./index.jsx'
]
},
output: {
path: __dirname,
filename: "[name].js",
publicPath: 'http://localhost:8881/',
chunkFilename: '[id].chunk.js',
sourceMapFilename: '[name].map'
},
resolve: {
extensions: ['', '.js', '.jsx', '.es6'],
modulesDirectories: ['node_modules']
},
module: {
loaders: [
{test: /\.jsx$|\.es6$|\.js$/, loaders: ['react-hot', 'babel-loader'], exclude: /node_modules/},
{test: /\.scss$|\.css$/, loader: 'style-loader!style!css!sass'}
]
},
plugins: [
new webpack.NoErrorsPlugin()
],
devtool: "eval-source-map",
devServer: {
port: 8080,
historyApiFallback: {
index: '/'
}
},
externals: {
'Config': JSON.stringify({
serverUrl: "http://pss/",
authSuccessUrl: "http://localhost:8881/loginSuccess",
podioClientId: "property-seller-solutions"
})
}
};
package.json 文件:
{
"name": "pss",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --hot --port 8080"
},
"author": "",
"license": "BSD-2-Clause",
"devDependencies": {
"babel": "~6.5.2",
"babel-core": "~6.9.1",
"babel-loader": "~6.2.4",
"babel-preset-es2015": "~6.9.0",
"babel-preset-react": "~6.5.0",
"babel-preset-stage-0": "~6.5.0",
"gulp": "^3.9.1",
"gulp-concat": "^2.6.0",
"gulp-html-replace": "^1.6.1",
"gulp-react": "^3.1.0",
"gulp-uglify": "^1.5.4",
"history": "~3.0.0",
"react": "~15.1.0",
"react-dom": "~15.1.0",
"react-hot-loader": "~1.3.0",
"webpack": "~1.13.1",
"webpack-dev-server": "~1.14.1"
},
"dependencies": {
"chart.js": "^2.1.6",
"connect-history-api-fallback": "~1.2.0",
"halogen": "^0.2.0",
"highcharts": "^4.2.5",
"react-d3-basic": "^1.6.11",
"react-infinite-scroll-component": "^1.4.1",
"react-infinite-scroll-es2015": "^1.0.0"
}
}
.htaccess 文件:
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
构建应用程序(webpack --hot --inline)后,得到两个输出文件 - index.js 和 index.html
我将这两个文件和 .htaccess 文件复制到我的本地主机根文件夹中。
索引路由工作正常..( http://localhost ),但是当我尝试重定向到 http://localhost/home 时它显示“404 Not Found”错误(在此服务器上找不到请求的 URL/home。)
当我使用 webpack 服务器(npm start)运行应用程序时,这些路由工作正常 - http://localhost:8080/home
最佳答案
工作了。
使用以下 .htaccess 代码:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /index.html [L]
并使用以下终端命令使用 webpack 构建项目:
webpack --inline --history-api-fallback --progress -p
关于.htaccess - 使用 webpack 构建应用程序后 React 路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38123519/