UNPKG

rollup-plugin-postcss-modules

Version:

rollup-plugin-postcss wrapper with built-in CSS module and TypeScript support

69 lines 2.87 kB
import { promises as fs } from 'fs'; import * as path from 'path'; import camelcase from 'camelcase'; import postcss from 'rollup-plugin-postcss'; import reserved from 'reserved-words'; function fixname(name) { const ccName = camelcase(name); return reserved.check(ccName) ? `$${ccName}$` : ccName; } const formatCSSDefinition = (name, classNames) => `\ ${classNames.filter((n) => !/-/.test(n)).map((t) => `export const ${t}: string`).join('\n')} interface Namespace { ${classNames.map((t) => `${JSON.stringify(t)}: string,`).join('\n\t')} } declare const ${name}: Namespace export default ${name}`; async function writeCSSDefinition(cssPath, classNames) { const name = fixname(path.basename(cssPath, '.css')); const definition = formatCSSDefinition(name, classNames); const dPath = `${cssPath}.d.ts`; await fs.writeFile(dPath, `${definition}\n`); return dPath; } class CSSExports { constructor(writeDefinitions) { this.definitionCB = async (dPath) => { if (typeof this.writeDefinitions === 'function') { await Promise.resolve(this.writeDefinitions(dPath)); } else { console.log(`${dPath} written`); } }; this.getJSON = async (id, exportTokens) => { const ccTokens = {}; for (const className of Object.keys(exportTokens)) { ccTokens[fixname(className)] = exportTokens[className]; ccTokens[className] = exportTokens[className]; } if (this.writeDefinitions) { const dPath = await writeCSSDefinition(id, Object.keys(ccTokens)); await this.definitionCB(dPath); } }; this.writeDefinitions = writeDefinitions; } } export default function eslintPluginPostCSSModules(options = {}) { const { plugins = [], writeDefinitions = false, modules = {}, namedExports = fixname, ...rest } = options; if ('getExport' in rest) { throw new Error("'getExport' is no longer supported."); } if (plugins.some((p) => p.postcssPlugin === 'postcss-modules')) { throw new Error("'rollup-plugin-postcss-modules' provides a 'postcss-modules' plugin, you cannot specify your own. Use the `modules` config key for configuration."); } const modulesOptions = modules === true ? {} : modules; if (modulesOptions === false || modulesOptions.getJSON) { throw new Error("'rollup-plugin-postcss-modules' provides a 'postcss-modules' plugin and its `getJSON()`. You cannot specify `modules.getJSON`"); } const { getJSON } = new CSSExports(writeDefinitions); return postcss({ plugins: [...plugins], modules: { getJSON, ...modulesOptions }, autoModules: false, namedExports, ...rest, }); } //# sourceMappingURL=index.js.map