react 路由刷新報錯問題

情況1:雙層路由 /a/b刷新報錯, react router 的bug ,瀏覽器解析會導致資源地址錯誤

查閱的各種帖子,什麼 ngnix 配置;都不好使。解決辦法 換成單級路由  /a_b

情況2: ngnix配置過濾時和 路由名字重複,這個改名字

附帶一個:react 使用 react-app-rewired 啓動項目配置:package.json 和  config-overrides.js

// package.json

{
  "name": "version_ui",
  "version": "0.1.0",
  "private": true,
  "homepage": ".",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "antd": "^3.26.12",
    "history": "^4.10.1",
    "isomorphic-fetch": "^2.2.1",
    "moment": "^2.24.0",
    "notificationcenter": "^1.1.0",
    "number-precision": "^1.3.2",
    "polished": "^3.4.4",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-loadable": "^5.5.0",
    "react-router": "^5.1.2",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0",
    "store2": "^2.10.0",
    "wangeditor": "^3.1.1",
    "webpack-build-notifier": "^2.0.0"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-app-rewired eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/plugin-proposal-decorators": "^7.8.3",
    "babel-plugin-import": "^1.13.0",
    "babel-polyfill": "^6.26.0",
    "css-loader": "^3.4.2",
    "customize-cra": "^0.9.1",
    "less": "^3.11.1",
    "less-loader": "^5.0.0",
    "mini-css-extract-plugin": "^0.9.0",
    "react-app-rewired": "^2.1.5"
  }
}
// config-overrides.js

const {
  override,
  addLessLoader,
  fixBabelImports,
  addBabelPlugin,
  addBabelPlugins,
  useBabelRc,
  useEslintRc,
  addWebpackAlias,
  addDecoratorsLegacy,
  overrideDevServer,
  addWebpackPlugin
} = require("customize-cra");
// const rewireReactHotLoader = require("react-app-rewire-hot-loader");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// 打包完成桌面提醒
// const WebpackBuildNotifierPlugin = require("webpack-build-notifier");
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");

// const ProgressBarPlugin = require('progress-bar-webpack-plugin')

// const Dashboard = require('webpack-dashboard')
// const DashboardPlugin = require('webpack-dashboard/plugin')
// const dashboard = new Dashboard()

const path = require("path");
// const fs = require("fs");
//讀取envURL.json文件
// const envURL = fs.readFileSync(path.join(__dirname, 'public/envURL.json'), "utf-8");
// 跨域配置
const devServerConfig = () => config => {
  return {
    ...config,
    port: 9000,
    historyApiFallback: true,
    // 服務開啓gzip
    // compress: true,
    // proxy: {
    //   "/api": {
    //     target: "http://192.168.4.195:2021/version",
    //     changeOrigin: true,
    //     pathRewrite: {
    //       "^/api": "/api",
    //     },
    //   }
    // }
  }
}
// const proxyApi = {
//   '/api': {
//     target: JSON.parse(envURL).version, // prod 
//     changeOrigin: true,
//     secure: false,
//     xfwd: false,
//     pathRewrite: {
//       "^/api": "/"
//     }
//   },
//   "/store": {
//     // target: '', // staging
//     changeOrigin: true,
//     secure: false,
//     xfwd: false,
//     pathRewrite: {
//       "^/store": "/"
//     }
//   }
// }
// 關閉sourceMap
const rewiredMap = () => config => {
  config.devtool = config.mode === "development" ? "cheap-module-source-map" : false

  return config
}
// 熱跟新
// const hotLoader = () => (config, env) => {
//   config = rewireReactHotLoader(config, env)
//   return config
// }
//生產環境去除console.* functions
const dropConsole = () => {
  return config => {
    if (config.optimization.minimizer) {
      config.optimization.minimizer.forEach(minimizer => {
        if (minimizer.constructor.name === "TerserPlugin") {
          minimizer.options.terserOptions.compress.drop_console = true
        }
      })
    }
    return config
  }
}
// const delConflictingOrder = () => {
//   return config => {
//     for (let i = 0; i < config.plugins.length; i++) {
//       const p = config.plugins[i]
//       if (!!p.constructor && p.constructor.name === MiniCssExtractPlugin.name) {
//         const miniCssExtractOptions = { ...p.options, ignoreOrder: true }
//         config.plugins[i] = new MiniCssExtractPlugin(miniCssExtractOptions)
//         break
//       }
//     }
//   }
// }
// const addMiniCssExtractPlugin = () => {
//   return config => {
//     config.plugins.unshift(
//       new FilterWarningsPlugin({
//         // exclude: /any-warnings-matching-this-will-be-hidden/
//         // exclude: /mini-css-extract-plugin[^]*Conflicting order between:/
//         exclude: /\[mini-css-extract-plugin\][^]*Conflicting order between:/
//       })
//     )
//   }
// };
const srcOuterScope = () => {
  return config => {
    config.resolve.plugins = config.resolve.plugins.filter(plugin => !(plugin instanceof ModuleScopePlugin));
    return config;
  }
}
const addPolyfill = () => {
  return config => {
    config.entry.unshift("babel-polyfill");
    return config;
  }
}
module.exports = {
  webpack: override(
    fixBabelImports("import", {
      libraryName: "antd",
      libraryDirectory: "es",
      style: true
    }),
    addLessLoader({
      // strictMath: true,
      // noIeCompat: true,
      javascriptEnabled: true,
      modifyVars: { "@primary-color": "#cc0000" }
    }),
    // 配置babel解析器
    addBabelPlugin(["@babel/plugin-proposal-decorators", { legacy: true }]),
    // ...addBabelPlugins(
    //  ["@babel/plugin-proposal-decorators", {"legacy": true}]
    // ),
    // useBabelRc(),
    addWebpackAlias({
      ["@"]: path.resolve(__dirname, "src"),
      ["@public"]: path.resolve(__dirname, "public"),
      ["@pages"]: path.resolve(__dirname, "src/pages"),
      ["@component"]: path.resolve(__dirname, "src/component"),
      ["@utils"]: path.resolve(__dirname, "src/utils")
    }),
    // 啓用裝飾器語法
    // addDecoratorsLegacy(),
    useEslintRc(".eslintrc"),
    // 關閉mapSource
    rewiredMap(),
    // 熱跟新
    // hotLoader(),
    dropConsole(),
    // src以外引入文件
    srcOuterScope(),
    // 對es6、7語法進行低版本瀏覽器再次降級;
    addPolyfill(),
    // 打包編譯完成提醒
    // addWebpackPlugin(
    //   new WebpackBuildNotifierPlugin({
    //     title: "唐泉版本管理系統",
    //     logo: path.resolve(""),
    //     suppressSuccess: true
    //   }),
    //   new MiniCssExtractPlugin({
    //     filename: "static/css/[name].[contenthash].css",
    //     chunkFilename: "static/css/[id].[contenthash].css",
    //     ignoreOrder: false
    //     // moduleFilename: ({ name }) => `${name.replace('/js/', '/css/')}.css`
    //   }),
    //   // 美化控制檯
    //   // new DashboardPlugin(dashboard.setData),
    //   // 進度條
    //   // new ProgressBarPlugin(),
    //   delConflictingOrder(),
    //   addMiniCssExtractPlugin(),
    // ),
  ),
  devServer: overrideDevServer(
    devServerConfig()
  )
  // devServer: configFunction => (proxy, allowedHost) => {
  //   proxy = process.env.NODE_ENV === "development" ? proxyApi : proxyApi
  //   // allowedHost: 添加額外的地址
  //   const config = configFunction(proxy, allowedHost)
  //   return config
  // }
};

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章