【问题标题】:How to force webpack to put the plain CSS code into HTML head's style tag?如何强制 webpack 将纯 CSS 代码放入 HTML 头部的样式标签中?
【发布时间】:2019-05-08 06:47:13
【问题描述】:

我有这个webpack.config

const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInlineStylePlugin = require('html-webpack-inline-style-plugin');
const path = require('path');

module.exports = {
  mode: 'production',
  entry: {
    main: [
      './src/scss/main.scss'
    ]
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '',
    filename: 'js/[name].js'
  },
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true
      })
    ]
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          'css-loader',
          'sass-loader',
        ]
      },
      // ... other stuffs for images
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/main.html',
      filename: 'main.html'
    }),
    new HtmlWebpackInlineStylePlugin()
  ]
};

我试过这个配置,但效果不好,因为 CSS 代码生成到 main.css 文件中。

但如果我将 CSS 代码作为<style> 直接写入<head> 标签,它就可以工作。

如何设置 webpack 以将 Sass 文件中的 CSS 代码作为内联 CSS 放入 HTML

或者有没有勾选将 CSS 首先放入 <head>,然后 html-webpack-inline-style-plugin 插件可以解析它?

【问题讨论】:

    标签: html css webpack sass


    【解决方案1】:

    在只使用style-loader 之前我已经这样做了,默认情况下会将您的css 添加为<head> 标记处的内联样式。这不会生成任何输出 css 文件,只会创建一个/多个样式标签,其中包含所有样式。

    webpack.config.js

    module.exports = {
      //... your config
    
      module: {
        rules: [
          {
            test: /\.scss$/, // or /\.css$/i if you aren't using sass
            use: [
              {
                loader: 'style-loader',
                options: { 
                    insert: 'head', // insert style tag inside of <head>
                    injectType: 'singletonStyleTag' // this is for wrap all your style in just one style tag
                },
              },
              "css-loader",
              "sass-loader"
            ],
          },
        ]
      },
    
      //... rest of your config
    };
    

    index.js入口点脚本

    import './css/styles.css';
    

    【讨论】:

    • 你有没有机会拼凑一个要点来展示一个完整的例子?我已经在我的配置中包含了您推荐的逻辑,并进行了少量修改(我试图在 HTML 而不是 scss 文件中内联 vanilla css 链接),虽然我没有收到任何错误,但配置似乎忽略了我的 css。
    • @AlexanderTsepkov 这仅在您在 main.js (import style from './file.css';) 中导入 main.css 或者您有问题中的样式条目时才有效。就像下面的例子github.com/webpack-contrib/style-loader#usage 看看。另外,如果你分享一个链接,我可以看到你的代码,如果需要新的东西,我可以帮助你并更新我的 awnser。
    猜你喜欢
    • 2014-05-08
    • 2021-06-20
    • 2011-07-10
    • 2017-12-21
    • 1970-01-01
    • 2020-12-10
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多