无法在 Webpack 中使用 html-loader 在主 HTML 文件中包含 HTML 部分

问题描述 投票:0回答:1

#emergencyHelpNeeded 我是一个初学者,正在学习一些前端人员。我最近三天一直在努力解决这个问题。我正在尝试使用 Webpack 配置中的 html-loader 将 HTML 部分包含到我的主 HTML 文件中。尽管遵循了各种教程和解决方案,我仍然遇到问题。我也尝试过这个,但无法弄清楚。如果你能帮我摆脱这个问题,我将不胜感激。

我尝试过,仍然没有得到任何解决方案。 有没有办法使用 html-webpack-plugin 包含部分内容?

这是我的 webpack.config.js 文件

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const webpack = require("webpack");
const glob = require("glob");

module.exports = ({ mode }) => {
  const isProduction = mode === "production";

  return {
    entry: "./src/js/app.js",
    output: {
      path: path.resolve(__dirname, "dist"),
      filename: "js/app.bundle.js",
      clean: true,
    },
    devServer: {
      static: {
        directory: path.join(__dirname, "dist"),
      },
      compress: true,
      port: 3000,
      open: true,
      hot: true,
    },
    module: {
      rules: [
        {
          test: /\.(s[ac]ss|css)$/i,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : "style-loader",
            "css-loader",
            "postcss-loader",
            "sass-loader",
          ],
        },
        {
          test: /\.html$/i,
          loader: "html-loader",
        },
        {
          test: /\.(png|jpe?g|gif|svg|ico|eot|ttf|woff)$/i,
          type: "asset",
          generator: {
            filename: "images/[name][ext]",
          },
        },
        {
          test: /\.m?js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env"],
            },
          },
        },
      ],
    },
    resolve: {
      extensions: [".js"],
    },
    plugins: [
      ...glob.sync("./src/pages/**/*.html").map((file) => {
        return new HtmlWebpackPlugin({
          template: file,
          filename: path.basename(file),
          chunks: ["main"],
        });
      }),
      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
      }),
      ...(isProduction
        ? [
            new MiniCssExtractPlugin({
              filename: "css/[name].css",
            }),
            new ImageMinimizerPlugin({
              minimizer: {
                implementation: ImageMinimizerPlugin.imageminMinify,
                options: {
                  plugins: [
                    ["mozjpeg", { quality: 75 }],
                    ["pngquant", { quality: [0.65, 0.9], speed: 4 }],
                    ["svgo", { removeViewBox: false }],
                    ["gifsicle", { interlaced: true }],
                  ],
                },
              },
            }),
          ]
        : []),
    ],
    mode: isProduction ? "production" : "development",
  };
};

我在我的index.html和其他html页面中写了这个,但是当我运行npm run dev或npm run build时我得到了这个<%= require('html-loader!./partial/header.html').default %>。

<%= require('html-loader!./partial/header.html').default %>

请帮我解决这个问题。如果您需要更多信息,请告诉我。 预先感谢。

javascript webpack frontend micro-frontend webpack-html-loader
1个回答
0
投票

您可以尝试使用现代且强大的html-bundler-webpack-plugin而不是

html-webpack-plugin

使用 Bundler 插件,入口点是 HTML 模板。
所有源资源文件(脚本、样式、图像等)都可以使用

<script>
<link>
标签直接在 HTML 模板中指定。

该插件解析模板中资源的源文件,并在生成的 HTML 中将其替换为正确的输出 URL。 解析后的资源将通过 Webpack 插件/加载器进行处理并放入输出目录中。

HtmlBundlerPlugin 取代了许多插件和加载器的功能,例如:

  • html-webpack-插件
  • 迷你 CSS 提取插件
  • html-loader
  • 样式加载器
  • 还有许多其他

注意

默认情况下,HtmlBundlerPlugin 使用 Eta 模板引擎。 Eta 更快更小 EJS 替代方案。

HtmlBundlerPlugin 支持“开箱即用”的 Eta、EJS、Handlebars、Nunjucks、Pug、TwigJS 模板引擎。

例如有你的部分

./src/partials/header.html
:

<h1>My Header</h1>

例如,有您的页面模板

./src/pages/home/index.html

<html>
  <head>
    <!-- relative path to SCSS source file -->
    <link href="../scss/style.scss" rel="stylesheet" />
    <!-- relative path to JS source file -->
    <script src="../js/app.js" defer="defer"></script>
  </head>
  <body>
    <!-- the path is relative to project directory -->
    <%~ include('src/partials/header.html') %>
    
    <!-- relative path to image source file -->
    <img src="../images/picture.png" />
  </body>
</html>

Webpack 配置:

const path = require('path');
const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');
const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
const webpack = require('webpack');

module.exports = ({ mode }) => {
  const isProduction = mode === 'production';

  return {
    output: {
      path: path.resolve(__dirname, 'dist'),
      clean: true,
    },
    plugins: [
      new HtmlBundlerPlugin({
        // automatically processing all HTML pages in the directory recursively
        //entry: './src/pages',
        // - OR - define all pages manually
        entry: {
          index: './src/pages/home/index.html', // => generates dist/index.html
          'about/index': './src/pages/about/index.html', // => generates dist/about/index.html
          // add here your pages
        },
        js: {
          filename: 'js/[name].[contenthash:8].js', // JS output filename
        },
        css: {
          filename: 'css/[name].[contenthash:8].css', // CSS output filename
        },
      }),

      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
      }),
      ...(isProduction
        ? [
            new ImageMinimizerPlugin({
              minimizer: {
                implementation: ImageMinimizerPlugin.imageminMinify,
                options: {
                  plugins: [
                    ['mozjpeg', { quality: 75 }],
                    ['pngquant', { quality: [0.65, 0.9], speed: 4 }],
                    ['svgo', { removeViewBox: false }],
                    ['gifsicle', { interlaced: true }],
                  ],
                },
              },
            }),
          ]
        : []),
    ],
    module: {
      rules: [
        {
          test: /\.(s[ac]ss|css)$/i,
          use: ['css-loader', 'postcss-loader', 'sass-loader'],
        },
        {
          test: /\.(png|jpe?g|gif|svg|ico|eot|ttf|woff)$/i,
          type: 'asset',
          generator: {
            filename: 'images/[name][ext]',
          },
        },
        {
          test: /\.m?js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env'],
            },
          },
        },
      ],
    },
    resolve: {
      extensions: ['.js'],
    },
    mode: isProduction ? 'production' : 'development',
    devServer: {
      static: {
        directory: path.join(__dirname, 'dist'),
      },
      compress: true,
      port: 3000,
      open: true,
      hot: true,
    },
  };
};

附注您可以在 GitHub 上创建一个小型存储库,然后我可以帮助您完成您的项目。

© www.soinside.com 2019 - 2024. All rights reserved.