diff --git a/README.md b/README.md index 6f0ebcd..0bc1649 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,17 @@ postCssPlugin.default({ }); ``` +As per standard any file having `module` before the extension (ie `somefile.module.css`) will be treated as a module. +The option `fileIsModule` allows to override this behavior. + +```js +postCssPlugin.default({ + // pass a custom `fileIsModule` option to tell whether a file should be treated as a module + // in this example we want everything to be a module except file finishing with `global.css` + fileIsModule: (filepath) => !filepath.endsWith(".global.css") +}); +``` + ### Preprocessors To use preprocessors (`sass`, `scss`, `stylus`, `less`), just add the desired preprocessor as a `devDependency`: diff --git a/src/index.ts b/src/index.ts index 4e9fe35..1bf85ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -31,6 +31,7 @@ interface PostCSSPluginOptions { lessOptions?: Less.Options; stylusOptions?: StylusRenderOptions; writeToFile?: boolean; + fileIsModule?: (filename: string) => boolean; } interface CSSModule { @@ -47,7 +48,8 @@ export const defaultOptions: PostCSSPluginOptions = { sassOptions: {}, lessOptions: {}, stylusOptions: {}, - writeToFile: true + writeToFile: true, + fileIsModule: null }; const postCSSPlugin = ({ @@ -57,7 +59,8 @@ const postCSSPlugin = ({ sassOptions, lessOptions, stylusOptions, - writeToFile + writeToFile, + fileIsModule }: PostCSSPluginOptions = defaultOptions): Plugin => ({ name: "postcss2", setup(build) { @@ -101,7 +104,9 @@ const postCSSPlugin = ({ const sourceExt = path.extname(sourceFullPath); const sourceBaseName = path.basename(sourceFullPath, sourceExt); - const isModule = sourceBaseName.match(/\.module$/); + const isModule = fileIsModule + ? fileIsModule(sourceFullPath) + : sourceBaseName.match(/\.module$/); const sourceDir = path.dirname(sourceFullPath); let tmpFilePath: string; diff --git a/test/index.js b/test/index.js index 0095822..d09b56d 100644 --- a/test/index.js +++ b/test/index.js @@ -111,6 +111,33 @@ describe("PostCSS esbuild tests", () => { }) .catch(() => process.exit(1)); }); + + it("Works with custom module function", (done) => { + let testFilename = null; + build({ + entryPoints: ["tests/basic.ts"], + bundle: true, + outdir: "dist", + plugins: [ + postCSS.default({ + plugins: [autoprefixer, postCssImport], + modules: true, + fileIsModule: (filename) => { + testFilename = filename; + return false; + } + }) + ] + }) + .then(() => { + // ensure the proper filename was passed + assert.match(testFilename, /styles\/basic\.css/); + }) + .catch((e) => { + console.error(e); + process.exit(1); + }); + }); }); function test(entryPoint) {