webpack打包 CSS分离 mini-css-extract-plugin

Intro

优化目的:应用首屏加载时间太久,按不同策略/角度分离打包文件。

步骤

  • 安装依赖
    npm install -D mini-css-extract-plugin

  • 配置webpack配置文件

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

module.exports = {
  // ...
  
  plugins: [
    new HtmlWebpackPlugin({ template: "public/index.html" }),
    new MiniCssExtractPlugin({
      filename: "[hash:3].[name].css?v=[hash]",
      chunkFilename: "[hash:3].[id].css?v=[hash]",
      ignoreOrder: false,
      linkType: "text/css",
    }),
    // ...
  ],

  module: {
    rule: [
      // 处理CSS|less资源
      {
        test: /\.(css|less)$/,
        use: [
          // mini-css-extract-plugin 和 style-loader 是一样的功能(将JS字符串嵌入<style>标签内),不可以同时使用。
          MiniCssExtractPlugin.loader,
          // { loader: "style-loader" }, // 利用JS字符串创建样式节点 即<style>标签
          { loader: "css-loader" },   // CSS -> CommonJS模块
          {
            loader: "less-loader",
            options: {
              lessOptions: {
                javascriptEnabled: true,  // 解决报错: Inline JavaScript is not enabled. Is it set in your options?
              },
            },
          },  // 编译: less -> CSS
        ],
      },
    ],
  },
  
};

启动项目(开发环境或生产皆可)

通过对比,可看出在配置 mini-css-extract-plugin 的前后:
配置前:请求一个完整的JS文件。
配置后:请求独立的css与JS文件,文件大小之和等于之前整个JS文件的大小。

未分离css时(注意勾选Disable cache选项):
在这里插入图片描述

分离css之后:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
`mini-css-extract-plugin` 是一个 Webpack 插件,用于从 JavaScript bundle 中提取 CSS 到单独的文件中。与使用 `style-loader` 将 CSS 插入 `<style>` 标签不同,`mini-css-extract-plugin` 可以帮助您创建一个单独的 CSS 文件,该文件可以在浏览器中缓存,从而提高网站的性能和加载速度。 使用 `mini-css-extract-plugin` 非常简单。首先,您需要在 Webpack 配置文件中安装和导入插件: ```javascript const MiniCssExtractPlugin = require('mini-css-extract-plugin'); ``` 然后,您需要在插件配置中指定输出文件的名称和路径: ```javascript plugins: [ new MiniCssExtractPlugin({ filename: 'css/[name].[contenthash].css', }), ], ``` 在上面的代码中,`filename` 选项指定输出文件的名称和路径。`[name]` 会被替换为入口名称,`[contenthash]` 会被替换为根据文件内容生成的哈希值,这样可以确保每次构建生成的文件都有一个唯一的文件名。 最后,您需要在 Webpack 配置文件的加载器中使用 `mini-css-extract-plugin`,以便在构建期间从 JavaScript bundle 中提取 CSS: ```javascript module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'], }, ], }, ``` 在上面的代码中,`MiniCssExtractPlugin.loader` 用于从 JavaScript bundle 中提取 CSS,`css-loader` 用于将 CSS 转换为 JavaScript 可以理解的模块格式。这些加载器可以根据您的需要进行修改,以便处理不同类型的 CSS。 以上是使用 `mini-css-extract-plugin` 的基本步骤。使用此插件可以帮助您提高网站的性能和加载速度,特别是对于大型网站和长时间运行的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值