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

标签 webpack

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

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

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

请不要只说使用 https://www.npmjs.com/package/html-inline-css-webpack-plugin或引用Inline JavaScript and CSS with webpack ,因为这似乎受到错误和版本/依赖项不匹配的困扰。如果这是最佳答案,那么您实际上如何使其发挥作用?所有依赖项的哪些版本实际上可以协同工作?

这是我的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"

最佳答案

过去几周我一直在研究 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',
                ],
            },
        ],
    },
};

关于webpack - 如何使用webpack将css和js内联到html中并删除未使用的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64206486/

相关文章:

javascript - `import username from ' ./username.txt '` 与 typescript+webpack 给出 `undefined`

javascript - 仅从 ES6 模块导入静态变量

webpack - 如何修复 "Module not found: Error: Can' t resolve *"error

reactjs - ScrollMagic 与 React

javascript - CSS 加载器和提取文本插件用例 Webpack

javascript - webpack 2 预期 '!' 错误与导入一起使用

javascript - 如何使用 Webpack 代码分割来处理部署?

webpack - webpack-serve 与 webpack-dev-server 有何不同?

javascript - 在computed中导入组件和在vuejs动态导入中导入组件有什么区别?

reactjs - 如何使用外部CSS在Reactjs中设置背景图片?