开发者问题收集

如何使用 webpack 将 css 和 js 内联到 html 中并删除未使用的样式

2020-10-05
4059

我有一个 HTML 文件和一些 SASS 和 JS,对于生产,我想将它们捆绑在一起变成一个 HTML 文件,其中包含编译成 CSS 的 SASS 到内联 <style> 元素,以及组合并最小化为内联 <script> 元素的 JS。不是,其中 css 嵌入在 JS 中并通过 JS 或单独的文件添加到 DOM。

我已经将 SASS 编译成 .css<link ed 到,并将 JS 编译成 <script src=" ed .js 。我还让 PurgeCss 工作了(我认为 - 它剥离了很多可能未使用的选择器)。

如何在 HTML 中的自己的标签中内联 CSS 和 JS?

请不要只说使用 https://www.npmjs.com/package/html-inline-css-webpack-plugin 或参考 使用 webpack 内联 JavaScript 和 CSS ,因为这似乎充斥着错误和版本/依赖项不匹配。如果这是最佳答案,您实际上如何使其工作?所有依赖项的哪些版本实际上可以协同工作?

这是我的 webpack.config ,据我所知,它可以正常工作:

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

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
const glob = require('glob');

const purgecssFromHtml = require('purgecss-from-html');

const PATHS = {
  src: path.join(__dirname, 'src')
}

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/i,
        use: [
          
            MiniCssExtractPlugin.loader,
            //'style-loader',
            {
                loader: 'css-loader',
                options: {
                //importLoaders: 1,
                url: false
                },
            },
            'sass-loader',
        ],
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "src", "index.html")
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css"
    }),
    new PurgecssPlugin({
      paths: glob.sync(`${PATHS.src}/*.*`),
      styleExtensions: ['.css'],
      whitelist: ['whitelisted'],
      extractors: [
        {
          extractor: purgecssFromHtml,
          extensions: ['html']
        }
      ]
    })
  ]
};

src/index.js

import "./scss/theme.scss";
import "./file1.js"
import "./file2.js"
1个回答

过去几周我一直在研究 Webpack。

我对 Webpack 还不是很熟悉,但有一个 HTML 模板项目一直在用它,可能会有帮助: https://github.com/JustAGuyCoding/spotlight-webpack ,尤其是因为它是一个可行的示例。

Webpack 配置如下所示:

const path                      = require('path');
const HtmlWebpackPlugin         = require('html-webpack-plugin');
const { CleanWebpackPlugin }    = require('clean-webpack-plugin');
const MiniCssExtractPlugin      = require('mini-css-extract-plugin');
const StyleExtHtmlWebpackPlugin = require("style-ext-html-webpack-plugin");
const CopyPlugin                = require('copy-webpack-plugin');

module.exports = {

    entry: './src/spotlight.js',
    output: {
        path        : path.resolve(__dirname, 'dist'),
        filename    : 'spotlight.[contenthash].js',
    },

    /* Development - webmode. */
    // devtool: 'inline-source-map',
    // devServer: {
    //     contentBase: './dist',
    // },

    plugins: [

        new CleanWebpackPlugin({
            dry     : false,
            verbose : true,
        }),

        new HtmlWebpackPlugin({
            title           : 'Spotlight',
            filename        : 'index.html',
            template        : './src/spotlight.html',

            scriptLoading   : 'defer',
            inject          : false,
                /* Prevent automatic insertion of CSS link tag, as it will inlined, but specify postiion  of bundled.js in the lodash template. */

            /* _Lodash template params. */
            static: false
        }),

        new MiniCssExtractPlugin({
            filename        : 'spotlight.css',
            chunkFilename   : '[id].css',
        }),

        new StyleExtHtmlWebpackPlugin({
            position: 'head-bottom',
            minify: true
        }),

        new CopyPlugin({
            patterns: [
                { from: './license.txt', to: '../dist/license.txt' },
                { from: './notice.txt', to: '../dist/notice.txt' },
                { from: './readme_html.md', to: '../dist/readme.md' },
            ],
        }),
    ],
    module: {
        rules: [

            /* Images - uses require(lodash template), HtmlWebpackPlugin and file-loader to pickup and process(copy to dist).  */
            {
                test: /\.(png|svg|jpg|gif)$/,
                loader: 'file-loader',
                options: {
                    name: "images/[name].[ext]",
                    esModule: false
                    /* Fixes [object,object] appearing on spotlight.html template when require(file) processed by lodash in HtmlWebpackPlugin.*/
                }
            },

            /* SASS-CSS-Extract-Internalise\Inline - uses StyleExtHtmlWebpackPlugin*/
            {
                test: /\.s[ac]ss$/i,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                        },
                    },
                    'css-loader',
                    'sass-loader',
                ],
            },
        ],
    },
};
Anthony
2020-10-05