React 如何在 GitHub Pages 访问 index.html 以外其它路径问题

问题

GitHub Pages 生成的静态页面与 React SPA 页面冲突,由于 Pages 不能 Nginx 又不能 Node.js ,除了 index.html 路由以外其它路由都 404 错误。

方法

  1. build 后把 index.html 复制修改为 404.html ,不管什么路由页面找不到以后,都会跳转到 404 页面。 比如我的 「 VSCode 中文社区 」

  2. 第二种方法跟本主题有点远了,不能解决上面问题,只是记录找解决方案的时候,发现多页面生成配置,React 生成多页面入口。
    项目是 creat-react-app 脚手架创建,首先执行

npm run eject  

下来在 config 中修改 webpack.config.dev.js 文件

  entry: {
    index: [
      require.resolve('./polyfills'),
      require.resolve('react-dev-utils/webpackHotDevClient'),
      paths.appIndexJs,
    ],
    oauth: [
      require.resolve('./polyfills'),
      require.resolve('react-dev-utils/webpackHotDevClient'),
      paths.appSrc + '/oauth.js',
    ]
  },

修改plugins中的HtmlWebpackPlugin

    new HtmlWebpackPlugin({
      inject: true,
      chunks: ["index"],
      template: paths.appHtml,
    }),
    new HtmlWebpackPlugin({
      inject: true,
      chunks: ["oauth"],
      template: paths.appHtml,
      filename: 'oauth.html'
    }),

修改config下的webpack.config.prod.js文件

  entry:
    {
      index: [
        require.resolve('./polyfills'),
        paths.appIndexJs
      ],
      oauth: [
        require.resolve('./polyfills'),
        paths.appSrc + '/oauth.js'
      ]
    },

修改plugins中的HtmlWebpackPlugin

    new HtmlWebpackPlugin({
      inject: true,
      chunks: ["index"],
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    new HtmlWebpackPlugin({
      inject: true,
      chunks: ["oauth"],
      template: paths.appHtml,
      filename: 'oauth.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),

修改webpackDevServer.config.js

   historyApiFallback: {
      disableDotRule: true,
      rewrites: [
        { from: /^\/oauth.html/, to: '/build/oauth.html' }
      ]
    },

在 src 文件里增加一个页面 js 单文件 oauth.js

import React from 'react'
import ReactDOM from 'react-dom'
import Oauth from './js/oauth'
import registerServiceWorker from './registerServiceWorker'
ReactDOM.render(, document.getElementById('root'))
registerServiceWorker()

完成,GitHub 地址 「 VSCode 中文社区 」

你可能感兴趣的:(React 如何在 GitHub Pages 访问 index.html 以外其它路径问题)