无法使用webpack内联JS和CSS

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

过去两天我一直在处理这个问题,但无法解决。我尝试了 stackoverflow 中发布的其他一些步骤,但无法使其发挥作用,而且所有问题也都是 3-4 年前的问题。

我有一个构建文件夹,其中包含bundle.js、bundle.css 和index.html。 index.html 包含

<link href="bundle.css">
<script src="bundle.js">

我正在尝试使用 webpack 将bundle.js 和bundle.css 内联到index.html 中。我面临两个问题:

  1. JS 文件被内联,但 index.html 仍然有
    script src="bundle.js"
  2. CSS 根本不会内联,也不会出现在
    dist
    文件夹中

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>

    <title>Internal site</title>
    <script src='bundle.js'></script>
    <link rel='stylesheet' href='bundle.css'>
</head>
<body></body>
</html>

webpack.config.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const HtmlInlineCSSWebpackPlugin = require('html-inline-css-webpack-plugin').default;
const HtmlInlineScriptWebpackPlugin = require('html-inline-script-webpack-plugin');

module.exports = {
    context: path.resolve(__dirname, './internal_site/public/'),
    entry: {
        main: './bundle.js', // Entry JavaScript file
    },
    output: {
        filename: '[name].js', // Output JS bundle
        path: path.resolve(__dirname, 'dist'), // Output directory
        clean: true, // Clean output directory before build
    },
    module: {
        rules: [
            {
                test: /\.css$/, // Match CSS files
                use: [
                    'style-loader', // Extract CSS into separate files
                    'css-loader', // Resolve CSS imports
                ],
            },
        ],
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: './index.html', // Path to your index.html
            inject: 'body', // Inject scripts into the body

            minify: {
                collapseWhitespace: true, // Minify HTML
                removeComments: true, // Remove comments
            },
        }),
        new HtmlInlineCSSWebpackPlugin(), // Inline CSS into <style> tags
        new HtmlInlineScriptWebpackPlugin(), // Inline JavaScript into <script> tags
    ],
    optimization: {
        minimize: true,
        minimizer: [
            new (require('terser-webpack-plugin'))({
                extractComments: false, // Remove comments
            }),
        ],
    },
    mode: 'production',
};

版本:

"webpack": "^5.97.1",
"webpack-cli": "^6.0.1"
javascript html css npm webpack
1个回答
0
投票

为了轻松地将 JS 和 CSS 内联到 HTML 中,您可以使用 html-bundler-webpack-plugin

使用此插件,您的源 JS 和 SCSS/CSS 文件应直接在 HTML 中定义。 如果在 JS 中导入 CSS,那么在 HTML 中应该只定义源 JS 文件。

例如,有你的源JS文件./bundle.js:

import './style.css';

console.log('>> bundle');

script
标签放置在 HTML 中所需的位置(头部或正文中)。 完全相同的位置将在生成的 HTML 中内联 JS。 您不需要在 Webpack 条目中定义 JS 文件。 该插件自动解析 HTML 中的源 JS 文件。

./src/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Internal site</title>
    <!-- path to source CSS file relative to this HTML file -->
    <link rel='stylesheet' href='./bundle.css'>
</head>
<body>
  <h1>Hello World!</h1>
  <!-- path to source JS file relative to this HTML file -->
  <script src="./bundle.js"></script>
</body>
</html>

webpack.config.js

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

module.exports = {
    context: path.resolve(__dirname, './internal_site/public/'),
    output: {
        path: path.resolve(__dirname, 'dist'), // Output directory
        clean: true, // Clean output directory before build
    },
    module: {
        rules: [
            {
                test: /\.css$/, // Match CSS files
                use: [
                    'css-loader', // Resolve CSS imports
                ],
            },
        ],
    },
    plugins: [
        new HtmlBundlerPlugin({
          entry: {
            index: './index.html', // Path to your index.html
          },
          js: {
            // output filename of compiled JavaScript, used if inline is false
            filename: '[name].[contenthash:8].js',
            inline: true, // Inline JavaScript into <script> tags
          },
          css: {
            // output filename of extracted CSS, used if inline is false
            filename: '[name].[contenthash:8].css',
            inline: true, // Inline CSS into <style> tags
          },
          minify: true, // Enable minify HTML
          minifyOptions: {
            collapseWhitespace: true, // Minify HTML
            removeComments: true, // Remove comments
          },
        }),
    ],
    mode: 'production',
};

所有源 SCSS/CSS 和 JS 文件将通过 Webpack 进行处理,编译后的 CSS 和 JS 将内联到 HTML 中。 生成的 HTML 将包含内联 CSS 和 JS:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Internal site</title>
    <!-- inlined CSS from bundle.css -->
    <style>
      h1 {
        color: red;
      }
    </style>
    <!-- inlined CSS from style.css imported in bundle.js -->
    <style>
      body {
        font-size: 16px;
      }
    </style>
</head>
<body>
  <h1>Hello World!</h1>
  <!-- inlined JS -->
  <script>
    (() => {
      'use strict';
      console.log('>> bundle');
    })();
  </script>
</body>
</html>

Bundler 插件避免了提取注释,因此您不需要

terser-webpack-plugin
。 Bundler 插件取代了插件和加载器的功能:

  • html-webpack-插件
  • html-inline-css-webpack-plugin
  • html-内联-脚本-webpack-插件
  • 样式加载器
  • 以及许多其他插件和加载器

您可以在此处查看更多信息:

附注

您可以在 GitHub 上创建一个小型存储库,我可以帮助您配置您的项目。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.