【问题标题】:CSS not included in index.htmlCSS 未包含在 index.html 中
【发布时间】:2021-02-13 17:39:19
【问题描述】:

我有这个 webpack.config.js:

const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = [{
entry: ['./app/clientside/app.scss', './app/clientside/app.js'],
plugins: [
    new HtmlWebpackPlugin({
        title: 'Caching',
    }),
],
output: {
path: __dirname + '/private_html/_app/dist',
publicPath: '',
filename: '[contenthash].bundle.js'
},
module: {
rules: [
  {
    test: /\.scss$/,
    use: [
      {
        loader: 'file-loader',
        options: {
          name: '[contenthash].bundle.css',
        },
      },
      { loader: 'extract-loader' },
      { loader: 'css-loader' },

                { loader: 'postcss-loader',
                    options: {
                         plugins: () => [autoprefixer()]
                    }
                },
                {
                    loader: 'sass-loader',
                    options: {
                        implementation: require('sass'),
                        sassOptions: {
                            includePaths: ['./node_modules']
                        }
                    }
                },
    ]
  },
    {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
    },
     ] },
}];

生成了css和js文件,但是index.html中只包含了js文件:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Caching</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<script src="dd9a13efe757661de1fe.bundle.js"></script>
</body>
</html>

我希望有链接元素引用 css 文件。我试过谷歌,但似乎找不到正确的方向/关键字。我该如何解决这个问题?

【问题讨论】:

    标签: webpack html-webpack-plugin


    【解决方案1】:

    我可能会考虑为此目的使用 [MiniCssExtractPlugin][1],它与 HtmlWebpackPlugin 一起,将允许您在 HTML 文件中获取链接标签,指向您的 CSS 文件。

    我引用了 HtmlWebpackPlugin [文档][2]:

    如果您在 webpack 的输出中有任何 CSS 资源(例如,使用 MiniCssExtractPlugin 提取的 CSS),那么这些资源将包含在生成的 HTML 元素中的标签中。

    您还可以查看这个 SO [answer][3],它提出了一些在 HTML 中内联 CSS 的其他方法。

    如果您愿意,可以分享指向您的项目的链接,我可以尝试更具体地为您提供帮助。 [1]:https://webpack.js.org/plugins/mini-css-extract-plugin/ [2]:https://webpack.js.org/plugins/html-webpack-plugin/ [3]:https://stackoverflow.com/a/50770543/6098812

    【讨论】:

    • 感谢您为我指明了这个方向。我确实尝试过 MiniCssExtractPlugin,但显然加载程序的顺序很重要。感谢帮助,现在已经解决了!
    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2020-07-24
    • 2011-01-22
    相关资源
    最近更新 更多