【问题标题】:Add stylesheet link dynamically into html using webpack使用 webpack 将样式表链接动态添加到 html 中
【发布时间】:2019-08-02 08:41:27
【问题描述】:

想要运行 webpack,它在使用 mini-css-extract-plugin 后在 html 文件的标题中创建适当的样式表链接——类似于 html-webpack-plugin 添加适当的 JS 包(脚本标记)到 html 中。是否可以让 webpack + 插件执行此操作,还是我必须手动粘贴样式表标签(在 html 模板中)?

运行 webpack 4.28

【问题讨论】:

    标签: webpack html-webpack-plugin mini-css-extract-plugin


    【解决方案1】:

    我相信这个 webpack 配置应该可以解决你的问题。

    const path = require('path');
    const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    
    module.exports = {
      entry: './src/index.js',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
      },
      plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
        }),
        new MiniCssExtractPlugin({
          filename: '[name].css',
        }),
      ],
      module: {
        rules: [
          {
            test: /\.scss$/,
            use: [
                { loader: MiniCssExtractPlugin.loader },
                'css-loader',
                'sass-loader'
            ],
          },
        ],
      },
    };
    

    当我试图回答同样的问题时,我需要理解的重要部分是 webpack 中规则和插件的顺序很重要。 (webpack 首先处理每个数组中的最后一项,然后继续处理,直到它到达第一项......这个post 支持这一点,以及 Sean Larkin 的前端大师教程。)

    在这种情况下,您需要在插件数组中的“HtmlWebpackPlugin”之后出现“MiniCSSExtractPlugin”。

    当然,您还需要在 /src 文件夹中包含 sass 文件和 index.js 文件,并在 index.js 中包含 import './style.scss' - 如果您还需要在 /src 中包含 index.html您将像我在配置文件中那样使用 HtmlWebpackPlugin 的模板选项。总而言之,这应该输出一个 main.css 文件、一个 bundle.js 文件和一个包含链接和脚本标记的 index.html,所有这些都在“dist”文件夹中。

    【讨论】:

      猜你喜欢
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      相关资源
      最近更新 更多