reactjs 如何配置webpack,以便能够提供静态html文件沿着react应用程序

flseospp  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(213)

我正在尝试使用Webpack构建一个react应用程序,Webpack为HTML静态文件保留了一些路径,但没有将它们导入react应用程序,如下面的示例所示。

预期结果:

localhost:3000/any/other/path -> load React
localhost:3000/test.html -> load HTML file

当前结果

localhost:3000/any/other/path -> load React
localhost:3000/test.html -> redirect to localhost:3000/test -> load React (Default Route)

这是我的尝试

1.使用html-webpack-plugin定义另一个HTML文件

plugins: [
  ...
  new HtmlWebpackPlugin({
    template: "./public/index.html",
    hash: true,
  }),
  new HtmlWebpackPlugin({
    template: "./public/test.html",
    filename: "test.html",
    chunks: []
  })
]

1.使用copy-webpack-plugin将HTML文件复制到build目录。

这是我的webpack.config.js

require("dotenv").config();
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const webpack = require("webpack");
const { ModuleFederationPlugin } = webpack.container;
const deps = require("./package.json").dependencies;
const configs = require("./src/configs/build/configs.json");
configs.NPM_VERSION = require("./package.json").version;

const buildDate = new Date().toLocaleDateString();

module.exports = (_env, argv) => {
  return {
    entry: "./src/index.ts",
    mode: process.env.NODE_ENV || "development",
    output: {
      publicPath: `${configs.DOMAIN}/`,
    },
    devServer: {
      port: configs.PORT,
      open: true,
      historyApiFallback: true,
      hot: true,
      static: {
        watch: true,
      },
    },
    devtool: "source-map",
    resolve: {
      extensions: [".ts", ".tsx", ".js"],
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx|tsx|ts)$/,
          loader: "ts-loader",
          exclude: /node_modules/,
        },
        {
          test: /\.(css|scss|sass)$/,
          use: ["style-loader", "css-loader", "postcss-loader"],
          exclude: /node_modules/,
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif)$/i,
          type: "asset/resource",
        },
        {
          test: /\.html$/i,
          loader: "html-loader",
        },
        {
          test: /\.tsx?$/,
          exclude: /node_modules/,
          use: [
            {
              loader: "dts-loader",
              options: {
                name: configs.APP_NAME,
                exposes: {},
                typesOutputDir: ".wp_federation",
              },
            },
          ],
        },
      ],
    },

    plugins: [
      new webpack.EnvironmentPlugin({ BUILD_DATE: buildDate }),
      new webpack.DefinePlugin({
        "process.env": JSON.stringify(configs),
      }),
      new HtmlWebpackPlugin({
        template: "./public/index.html",
        hash: true,
      })
    ],
  };
};
vsaztqbk

vsaztqbk1#

你应该在你的项目根目录下有一个名为public的文件夹,任何HTML文件都是相对于URL根目录的。

相关问题