在webpack构建之后,为什么我的反应路由工作不起作用?

时间:2018-03-02 12:30:38

标签: javascript reactjs webpack react-router

我做了一个简单的反应路由器。当我开发它时,我使用npm start命令启动了一个开发服务器。一切都在运作。但是当我使用命令npm run build(使用webpack)构建我的应用程序时,启动了一个简单的http服务器并转到/ add_project,出现404错误。而且我不知道为什么会这样。求救!

以下是代码:

App.js

imports...

render() {
    return (
        <Switch>
            <div>
                <Route exact path='/' component={Projects}/>
                <Route exact path='/add_project' component={AddProject} />
            </div>
        </Switch>
    );
}}

index.js

imports...

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
    document.getElementById('root')
);

webpack.config.js

const HtmlPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src',
  output: {
    filename: 'app.js',
    path: __dirname + '/dist'
  },
  devtool: 'source-map',
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    }]
  },
  plugins: [
    new HtmlPlugin({
      template: 'public/index.html'
    })
  ]
}

UPD:

的package.json

{
  "name": "Test",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack -p --progress --config webpack.config.js",
    "dev-build": "webpack --progress -d --config webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --progress -d --config webpack.config.js --watch",
    "start": "react-scripts start"
  },
  "license": "MIT",
  "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  },
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "bootstrap": "^4.0.0",
    "css-loader": "^0.28.4",
    "eslint": "^4.18.1",
    "eslint-plugin-react": "^7.7.0",
    "extract-text-webpack-plugin": "^2.1.2",
    "file-loader": "^0.11.2",
    "jquery": "^3.2.1",
    "react": "^15.6.1",
    "react-bootstrap": "^0.31.0",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.2.2",
    "style-loader": "^0.18.2",
    "webpack": "^3.11.0"
  }
}

UPD2:

AddProject.js

import React, { Component } from 'react';

class AddProject extends Component {
  constructor()
  {
    super();
  }

  render() {
    return (
      <form className="form-horizontal">
        <input type="text" ref="title" className="input" />
        <input type="text" ref=""/>
      </form>
    );
  }
}

export default AddProject;

1 个答案:

答案 0 :(得分:0)

您已经准确地将路径与&#39; /&#39;匹配。然后再次使用/ add_project路由进行匹配。尝试更改

     <Route exact path='/add_project' component=
       {AddProject} />

      <Route path='/add_project' component=
       {AddProject} />

如果在父路线上设置了精确,则子路线不匹配,但404将按预期呈现