Webpack 只打包 CSS

背景

Webpack 作为热门前端构建打包工具,常用来构建打包应用型项目,包含 HTML、JavaScript、CSS 等代码。但是遇到比较零散的项目,往往需要单独打包某一模块,比如:CSS。

解决方案

Webpack 单独打包 CSS 的话,规避不了必要的入口文件,这时候需要一个“傀儡”入口文件,例如:style.jsindex.style.html

style.js

import '../style/style.scss';

index.style.html

<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset=UTF-8>
  <meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
  <meta http-equiv=X-UA-Compatible content="ie=edge">
  <meta name=format-detection content="telephone=no,date=no,address=no,email=no,url=no">
  <title>page1</title>
</head>
<body>page1</body>
</html>

Webpack 配置 webpack.config.style.js

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: './temp/style.js',
  output: {
    filename: 'style.temp.js',
    path: path.resolve(__dirname, './temp')
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: `../style.min.css`
    }),
    new HtmlWebpackPlugin({
      filename: path.resolve(__dirname, './temp/index.temp.html'),
      template: path.resolve(__dirname, './temp/index.style.html'),
      inject: true,
      chunksSortMode: 'dependency'
    })
  ],
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注