@automattic/mini-css-extract-plugin-with-rtl

中文文档
0.8.0发布于 2019/11/27MITCommonJS近 30 天下载 2911

extracts CSS into separate files

原始使用文档
文档目录11 节
  1. Usage
  2. Configuration
  3. Credits
  4. Install
  5. Usage
  6. Configuration
  7. Minimizing For Production
  8. Features
  9. Remove Order Warnings
  10. Media Query Plugin
  11. License

This plugin is a fork of mini-css-extract-plugin but with a support for WebpackRTLPlugin. Namely, it allows to load async CSS files depending of page's current direction. Please check mentioned packages to learn how to use them.

npm install --save-dev mini-css-extract-plugin-with-rtl

Usage

Configuration

webpack.config.js

const MiniCssExtractPlugin = require("mini-css-extract-plugin-with-rtl");
const WebpackRTLPlugin = require("webpack-rtl-plugin");

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
      rtlEnabled: true,
      // Global variable (e.g., `window.pageDir`) whose value determines whether to load the LTR or
      // RTL version of a CSS chunk at runtime. Value should be either `"ltr"` or `"rtl"`. If the
      // `rtlGlobalVar` option is not specified, we check `document.dir` by default.
      rtlGlobalVar: 'pageDir' 

    }),
    new WebpackRTLPlugin() // You must not pass filename option
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

Credits

Originally created by Maxim Valenko as beshanoe/mini-css-extract-plugin-with-rtl. Automattic updated the plugin to use the latest mini-css-extract-plugin upstream version, reorganized the commit structure to make the fork easier to maintain, and added support for data-webpack attribute in the <link> tags inserted into the HTML body.

Original mini-css-extract-plugin README continues from here


mini-css-extract-plugin

npm deps tests coverage chat

This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.

It builds on top of a new webpack v4 feature (module types) and requires webpack 4 to work.

Compared to the extract-text-webpack-plugin:

  • Async loading
  • No duplicate compilation (performance)
  • Easier to use
  • Specific to CSS

Install

npm install --save-dev mini-css-extract-plugin

Usage

Configuration

publicPath

Type: String|Function Default: the publicPath in webpackOptions.output

Specifies a custom public path for the target file(s).

Minimal example

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // all options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
      ignoreOrder: false, // Enable to remove warnings about conflicting order
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

publicPath function example

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: (resourcePath, context) => {
                // publicPath is the relative path of the resource to the context
                // e.g. for ./css/admin/main.css the publicPath will be ../../
                // while for ./css/main.css the publicPath will be ../
                return path.relative(path.dirname(resourcePath), context) + '/';
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

Advanced configuration example

This plugin should be used only on production builds without style-loader in the loaders chain, especially if you want to have HMR in development.

Here is an example to have both HMR in development and your styles extracted in a file for production builds.

(Loaders options left out for clarity, adapt accordingly to your needs.)

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const devMode = process.env.NODE_ENV !== 'production';

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: devMode ? '[name].css' : '[name].[hash].css',
      chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ],
      },
    ],
  },
};

Hot Module Reloading (HMR)

extract-mini-css-plugin supports hot reloading of actual css files in development. Some options are provided to enable HMR of both standard stylesheets and locally scoped CSS or CSS modules. Below is an example configuration of mini-css for HMR use with CSS modules.

While we attempt to hmr css-modules. It is not easy to perform when code-splitting with custom chunk names. reloadAll is an option that should only be enabled if HMR isn't working correctly. The core challenge with css-modules is that when code-split, the chunk ids can and do end up different compared to the filename.

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // only enable hot in development
              hmr: process.env.NODE_ENV === 'development',
              // if hmr does not work, this is a forceful method.
              reloadAll: true,
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

Minimizing For Production

To minify the output, use a plugin like optimize-css-assets-webpack-plugin. Setting optimization.minimizer overrides the defaults provided by webpack, so make sure to also specify a JS minimizer:

webpack.config.js

const TerserJSPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
  optimization: {
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};

Features

Using preloaded or inlined CSS

The runtime code detects already added CSS via <link> or <style> tag. This can be useful when injecting CSS on server-side for Server-Side-Rendering. The href of the <link> tag has to match the URL that will be used for loading the CSS chunk. The data-href attribute can be used for <link> and <style> too. When inlining CSS data-href must be used.

Extracting all CSS in a single file

Similar to what extract-text-webpack-plugin does, the CSS can be extracted in one CSS file using optimization.splitChunks.cacheGroups.

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true,
        },
      },
    },
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};

Extracting CSS based on entry

You may also extract the CSS based on the webpack entry name. This is especially useful if you import routes dynamically but want to keep your CSS bundled according to entry. This also prevents the CSS duplication issue one had with the ExtractTextPlugin.

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

function recursiveIssuer(m) {
  if (m.issuer) {
    return recursiveIssuer(m.issuer);
  } else if (m.name) {
    return m.name;
  } else {
    return false;
  }
}

module.exports = {
  entry: {
    foo: path.resolve(__dirname, 'src/foo'),
    bar: path.resolve(__dirname, 'src/bar'),
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        fooStyles: {
          name: 'foo',
          test: (m, c, entry = 'foo') =>
            m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
          chunks: 'all',
          enforce: true,
        },
        barStyles: {
          name: 'bar',
          test: (m, c, entry = 'bar') =>
            m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
          chunks: 'all',
          enforce: true,
        },
      },
    },
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};

Module Filename Option

With the moduleFilename option you can use chunk data to customize the filename. This is particularly useful when dealing with multiple entry points and wanting to get more control out of the filename for a given entry point/chunk. In the example below, we'll use moduleFilename to output the generated css into a different directory.

const miniCssExtractPlugin = new MiniCssExtractPlugin({
  moduleFilename: ({ name }) => `${name.replace('/js/', '/css/')}.css`,
});

Long Term Caching

For long term caching use filename: "[contenthash].css". Optionally add [name].

Remove Order Warnings

For projects where css ordering has been mitigated through consistent use of scoping or naming conventions, the css order warnings can be disabled by setting the ignoreOrder flag to true for the plugin.

new MiniCssExtractPlugin({
  ignoreOrder: true,
}),

Media Query Plugin

If you'd like to extract the media queries from the extracted CSS (so mobile users don't need to load desktop or tablet specific CSS anymore) you should use one of the following plugins:

License

MIT

版本与发布记录

@automattic/mini-css-extract-plugin-with-rtl 共发布 1 个版本,首次发布于 2019/11/27;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.8.0latest2019/11/276 年前

关于 @automattic/mini-css-extract-plugin-with-rtl 的常见问题

@automattic/mini-css-extract-plugin-with-rtl 是什么?

extracts CSS into separate files

如何安装 @automattic/mini-css-extract-plugin-with-rtl?

在项目目录运行 npm install @automattic/mini-css-extract-plugin-with-rtl,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:webpack(^4.4.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@automattic/mini-css-extract-plugin-with-rtl 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/automattic__mini-css-extract-plugin-with-rtl 是否存在。

@automattic/mini-css-extract-plugin-with-rtl 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@automattic/mini-css-extract-plugin-with-rtl 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 6.9.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@automattic/mini-css-extract-plugin-with-rtl 可以商用吗?

@automattic/mini-css-extract-plugin-with-rtl 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@automattic/mini-css-extract-plugin-with-rtl 的下载量有多少?

根据 npm 官方下载统计,@automattic/mini-css-extract-plugin-with-rtl 在 2026/10/07 – 2026/11/05 这 30 天内被下载 2,911 次,日均约 97 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@automattic/mini-css-extract-plugin-with-rtl 还在维护吗?

最新版本 0.8.0 发布于 2019/11/27(6 年前);至今共发布 1 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/11/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。