如何使用Webpack加载程序读取React js App中的本地html文件内容?

问题描述

我正在开发react js应用,并尝试在本地读取html文件内容。在特定条件下,我正在这样的变量中传递文件html数据:

let content = require(`../Designs/${data.path}.html`);

但这给了我错误:

模块解析失败:意外令牌(1:0)您可能需要一个 适当的加载程序来处理此文件类型,当前没有加载程序 配置为处理此文件。看到 https://webpack.js.org/concepts#loaders

为解决此问题,我创建了“ webpack.config.js”文件并安装了webpack,html-loader。我的样子是这样的:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins

module.exports = {
    module: {
        rules: [
            {
                test: /\.html$/,use: [
                    {
                        loader: "html-loader",options: { minimize: true }
                    }
                ]
            }
        ]
    },plugins: [
        new HtmlWebpackPlugin({
            template: './public/index.html',})
    ]
};

仍然出现相同的错误。请帮忙或提出一些建议,因为我是Webpack的新手。

解决方法

let content = require(`../Designs/${data.path}.html`);

上面的代码是动态模块导入。
这意味着模块路径是在运行时生成的(执行代码时)。 但是webpack无法处理此类导入。
因为创建捆绑包时它不知道模块的确切路径。
因此,我认为最好导入所有文件,然后在代码中在它们之间切换,而不是在运行时生成模块路径。

如果相信documentation中的最少示例足以满足您的需求。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...