最简单的方式使用webpack编译 less 输出多套css 样式

1,040 阅读1分钟
原文链接: github.com

Build Status Coverage Status Packagist webpack

English | 中文版

This library use to overwrite webpack config to output multiple themes in once compile.

Install

npm i webpack-multiple-themes-compile webpack-merge
# Optional.If you didn't install extract-text-webpack-plugin.
npm i extract-text-webpack-plugin

Example

Origin webpack.config.js

module.exports = {
  output: {
    path: outPutPath,
    filename: '[name].js',
    chunkFilename: '[name].js'
  }
  // There is another options.
};

Change the webpack.config.js file.

+ const merge = require('webpack-merge');
+ const multipleThemesCompile = require('webpack-multiple-themes-compile');
- module.exports = {
+ const webpackConfigs = {
  output: {
    path: outPutPath,
    filename: '[name].js',
    chunkFilename: '[name].js'
  }
  // There is another options.
};

+ module.exports = merge(
+   webpackConfigs,
+   multipleThemesCompile({
+     themesConfig: {
+       green: {
+         color: '#008000'
+       },
+       yellow: {
+         color: '#ffff00'
+       }
+     },
+     lessContent: 'body{color:@color}'
+   })
+ );

Output directory tree.

.
├── theme-green.css
├── theme-yellow.css
└── themes.js

API

/**
 * @param configs
 */
multipleThemesCompile(configs);

configs

Property Type(Default) Description
styleLoaders Array [{ loader: 'css-loader' }, { loader: 'less-loader' }] The loaders to compile less.Details in webpack homepage
themesConfig* Object Theme configuration. key for the file name of the generated css, value for the object .The object's key, the value is the name of the variable to be overwritten, and the value of the variable.
lessContent String @import "../index"; The content of cache less.
preHeader String // Generate by Script. The header of generate files.
cacheDir String ./src/less/themes Cache Directory.
cwd String __dirname Relative output directory.
outputName (themeName:String,fileName:String) => String themeName => `${themeName}.css` Finally output pathname.

Notice

If you used html-webpack-plugin,maybe you need added this config:

 new HtmlwebpackPlugin({
   filename: 'index.html',
   template: 'src/index.html',
   inject: 'body',
   // exclude themes.js
+  excludeChunks: ['themes']
 })