postcssPlugin.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. const createStylelint = require('./createStylelint');
  3. const path = require('path');
  4. /** @typedef {import('stylelint').PostcssPluginOptions} PostcssPluginOptions */
  5. /** @typedef {import('stylelint').Config} StylelintConfig */
  6. /**
  7. * @type {import('postcss').PluginCreator<PostcssPluginOptions>}
  8. * */
  9. module.exports = (options = {}) => {
  10. const [cwd, tailoredOptions] = isConfig(options)
  11. ? [process.cwd(), { config: options }]
  12. : [options.cwd || process.cwd(), options];
  13. const stylelint = createStylelint(tailoredOptions);
  14. return {
  15. postcssPlugin: 'stylelint',
  16. Once(root, { result }) {
  17. let filePath = root.source && root.source.input.file;
  18. if (filePath && !path.isAbsolute(filePath)) {
  19. filePath = path.join(cwd, filePath);
  20. }
  21. return stylelint._lintSource({
  22. filePath,
  23. existingPostcssResult: result,
  24. });
  25. },
  26. };
  27. };
  28. module.exports.postcss = true;
  29. /**
  30. * @param {PostcssPluginOptions} options
  31. * @returns {options is StylelintConfig}
  32. */
  33. function isConfig(options) {
  34. return 'rules' in options;
  35. }