How to use the plugin function from postcss

Find comprehensive JavaScript postcss.plugin code examples handpicked from public code repositorys.

postcss.plugin is a function that creates a PostCSS plugin with specified behavior that can be added to a PostCSS processing pipeline.

3
4
5
6
7
8
9
10
11
12
    rootSelector: ':root',
    typeRatio: 1.2,
    ratioProperty: '--type-ratio'
}

module.exports = postcss.plugin('type-scale', (opts = defaults) => {
    const options = Object.assign(defaults, opts)

    return css => {
        const typeRatio = getTypeRatio(css, options)
fork icon73
star icon940
watch icon36

+ 5 other calls in file

62
63
64
65
66
67
68
69
70
71
                })
        });
});

// plugin
const prettier = postcss.plugin('postcss-prettier', () => root => {
        const raws = {
                decl: {
                        before: '\n\t',
                        between: ': '
fork icon19
star icon271
watch icon10

+ 11 other calls in file

How does postcss.plugin work?

postcss.plugin is a factory function that takes two arguments: the plugin name and a function that defines the plugin's behavior. The function should return an object with a postcss method, which takes two arguments: the CSS tree and a result object. The postcss method should apply the desired transformations to the CSS tree and update the result object.

Once the plugin function is defined, it can be added to a PostCSS processing pipeline using the .use() method, which accepts the plugin function as an argument.

When PostCSS processes CSS, it passes the CSS through each plugin in the processing pipeline, with each plugin transforming the CSS in some way. The output of one plugin is passed to the next plugin in the pipeline until all plugins have been executed. Finally, the processed CSS is returned as the output of the PostCSS processing pipeline.

8
9
10
11
12
13
14
15
16
17
let options = {}

/**
 * 替换标签名
 */
const replaceTagNamePlugin = postcss.plugin('replaceTagName', () => root => {
    const optimization = options.optimization || {}
    const wxssUniversalSelector = optimization.wxssUniversalSelector || 'taglist'

    root.walk(child => {
fork icon447
star icon0
watch icon94

+ 5 other calls in file

6
7
8
9
10
11
12
13
14
15
    }
  });
}

let allVariables;
module.exports = postcss.plugin('postcss-droproot', function() {
  allVariables = [];
  return (root, result) => {
    process(root);
  }
fork icon192
star icon0
watch icon48

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const postcss = require("postcss");

const pluginName = "example-plugin";

const examplePlugin = postcss.plugin(pluginName, () => {
  return (root, result) => {
    console.log(`[${pluginName}] Running...`);
    root.walkDecls((decl) => {
      if (decl.prop === "color") {
        decl.value = "red";
      }
    });
    console.log(`[${pluginName}] Complete.`);
  };
});

module.exports = examplePlugin;

In this example, the examplePlugin function is created using postcss.plugin. The plugin function takes two arguments: a plugin name and a function that returns another function. The returned function is the actual plugin that will be executed by PostCSS. This example plugin replaces the value of all CSS properties named "color" with the string "red". It also logs a message to the console when it starts and when it completes. To use this plugin in a PostCSS processing pipeline, you would add it to the pipeline using the .use() method: javascript Copy code

72
73
74
75
76
77
78
79
80
81

接下来是基本的包装器,用来包装我们的插件处理代码:
```
const postcss = require('postcss');

module.exports = postcss.plugin('myplugin', function myplugin(options) {

    return function (css) {

        options = options || {};
fork icon25
star icon70
watch icon12

8
9
10
11
12
13
14
15
16
17
 * Created by wangpanfe on 2019/11/25.
 */
'use strict';
const postcss = require('postcss');

const relativePathsPlugin = postcss.plugin('postcss-match-relative-paths', ({context, file}) => {
    return (root, result) => {
        root.walkAtRules('import', decl => {
            decl.params = decl.params.replace(/\.(wxss|css)/ig, '.' + context.rules.suffixMapping.css);
        });
fork icon17
star icon123
watch icon10

13
14
15
16
17
18
19
20
21
22

```js
---
filename: src/postcss-line-clamp.js
---
module.exports = postcss.plugin('postcss-line-clamp', function () {
  return function (root) {
    root.walkDecls(function (decl) {
      if (decl.prop === 'line-clamp') decl.prop = '-webkit-line-clamp'
    })
fork icon7
star icon37
watch icon3

15
16
17
18
19
20
21
22
23
24
postcssImport({
 plugins: [
   // On import, remove the comments from variables.pcss.css so they don't
   // appear as useless comments at the top files that import these
   // variables.
   postcss.plugin('remove-unwanted-comments-from-variables', (options) => {
     return css => {
       if (css.source.input.file.indexOf('variables.pcss.css') !== -1) {
         css.walk(node => {
           if (node.type === 'comment') {
fork icon4
star icon1
watch icon0

39
40
41
42
43
44
45
46
47
48
49
50
51




  result.warn('Greetings, time traveller. ' + 'We are in the golden age of prefix-less CSS, ' + 'where Autoprefixer is no longer needed for your stylesheet.');
}


module.exports = postcss.plugin('autoprefixer', function () {
  for (var _len = arguments.length, reqs = new Array(_len), _key = 0; _key < _len; _key++) {
    reqs[_key] = arguments[_key];
  }

fork icon0
star icon2
watch icon0

56
57
58
59
60
61
62
63
64
65
66
67
    visited[visitedId] = VISITED_MARKER;
    siblings.push(importId);
  }
}


module.exports = postcss.plugin('modules-extract-imports', function () {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};


  var failOnWrongOrder = options.failOnWrongOrder;

fork icon0
star icon0
watch icon1

+ 4 other calls in file

282
283
284
285
286
287
288
289
290
291
292
293
  if (isAnimationName) return localizeDeclValues(true, valuesNode, decl, context);


  return localizeDeclValues(false, valuesNode, decl, context);
}


module.exports = postcss.plugin('postcss-modules-local-by-default', function (options) {
  if (typeof options !== 'object') {
    options = {}; // If options is undefined or not an object the plugin fails
  }
  if(options && options.mode) {
fork icon0
star icon0
watch icon1

+ 4 other calls in file

262
263
264
265
266
267
268
      }
    )
  })
}


module.exports = postcss.plugin("postcss-import", AtImport)
fork icon0
star icon0
watch icon1

6
7
8
9
10
11
12
13
14
15
16
17


/**
 *
 * @type {Plugin}
 */
module.exports = postcss.plugin('postcss-url', (options) => {
    options = options || {};


    return function(styles, result) {
        const opts = result.opts;
fork icon0
star icon0
watch icon1

41
42
43
44
45
46
47
48
49
50
51
52


function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}


var index = postcss.plugin('postcss-color-gray', opts => root => {
  // walk all declarations likely containing a gray() function
  root.walkDecls(decl => {
    if (hasGrayFunction(decl)) {
      const originalValue = decl.value; // parse the declaration value
fork icon0
star icon0
watch icon1

436
437
438
439
440
441
442
443
444
445
446
  if (hasUrl) {
    return localizeDeclValues(false, decl, context);
  }
}


module.exports = postcss.plugin('postcss-modules-local-by-default', function(
  options
) {
  if (typeof options !== 'object') {
    options = {}; // If options is undefined or not an object the plugin fails
fork icon0
star icon0
watch icon1

20
21
22
23
24
25
26
27
28
29
30
  prop_white_list: "propList",
  media_query: "mediaQuery",
  propWhiteList: "propList"
};


module.exports = postcss.plugin("postcss-plugin-pxtoem", options => {
  convertLegacyOptions(options);
  const opts = Object.assign({}, defaults, options);
  const satisfyPropList = createPropListMatcher(opts.propList);

fork icon0
star icon0
watch icon1

+ 3 other calls in file

12
13
14
15
16
17
18
19
20
21
22
var extractImports = require("postcss-modules-extract-imports");
var modulesScope = require("postcss-modules-scope");
var modulesValues = require("postcss-modules-values");
var valueParser = require('postcss-value-parser');


var parserPlugin = postcss.plugin("css-loader-parser", function(options) {
	return function(css) {
		var imports = {};
		var exports = {};
		var importItems = [];
fork icon0
star icon0
watch icon0