gpt4 book ai didi

html - 如何强制 webpack 将纯 CSS 代码放入 HTML head 的样式标签中?

转载 作者:可可西里 更新时间:2023-11-01 13:42:23 26 4
gpt4 key购买 nike

我有这个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代码直接写入<head>标记为 <style> , 它正在工作。

我如何设置 webpack 来放置 CSS来自 Sass 的代码文件放入 HTML作为内联 CSS?

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

最佳答案

我之前只使用 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 - 如何强制 webpack 将纯 CSS 代码放入 HTML head 的样式标签中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53653652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com