Is it possible to have html-webpack-plugin generate <style> elements from css?

▼魔方 西西 提交于 2021-01-21 07:32:11

问题


I have a static site where I am using Vue and Webpack.

I have some global CSS rules in a file called style.css and I am importing them by using import './styles.css' from my index.js file. Additionally, I have some .vue files which generate their own CSS.

To generate the HTML page, I am using html-webpack-plugin.

My CSS rules appear to be applying correctly. However, the <style> tags which contain them are dynamically being added to the <head> of my page via the Javascript that Webpack generates. I would prefer these <style> tags to appear statically in the generated index.html file instead. Is there any way to achieve this?

Additionally, if possible, I would like the CSS to be minified.

This is my webpack configuration file:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html',
    }),
    new VueLoaderPlugin()
  ],
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ]
      }
    ]
  },
  mode: 'development'
};

回答1:


Sounds like the exact use case for these html-webpack plugins:

  • html-webpack-inline-source-plugin:

    It allows you to embed javascript and css source inline.

  • style-ext-html-webpack-plugin: an alternative to the previous one.

    If you use HtmlWebpackPlugin and ExtractTextPlugin in your Webpack builds to create HTML <link>s to external stylesheet files, add this plugin to convert the links to `~ elements containing internal (sometimes incorrectly called 'in-line') CSS.

  • html-inline-css-webpack-plugin: an alternative to style-ext-html-webpack-plugin.

    Convert external style sheet(<link rel="stylesheet"/>) to internal style sheet(<style>...<style/>). Require mini-css-extract-plugin and html-webpack-plugin

The last 2 HTML webpack plugins depend on one of the following webpack plugins:

  • Extract Text Plugin:

    Extract text from a bundle, or bundles, into a separate file. [...] It moves all the required *.css modules in entry chunks into a separate CSS file. So your styles are no longer inlined into the JS bundle, but in a separate CSS file (styles.css).

  • mini-css-extract-plugin: same as Extract Text Plugin, but for webpack v4.

    This plugin extracts CSS into separate files.



来源:https://stackoverflow.com/questions/50768575/is-it-possible-to-have-html-webpack-plugin-generate-style-elements-from-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!