Merge pull request #22 from gutenye/write-to-file

This commit is contained in:
Marton Lederer 2021-10-08 17:50:13 +02:00 committed by GitHub
commit 2a7a44882b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -30,6 +30,7 @@ interface PostCSSPluginOptions {
sassOptions?: SassOptions; sassOptions?: SassOptions;
lessOptions?: Less.Options; lessOptions?: Less.Options;
stylusOptions?: StylusRenderOptions; stylusOptions?: StylusRenderOptions;
writeToFile?: boolean;
} }
interface CSSModule { interface CSSModule {
@ -45,7 +46,8 @@ const postCSSPlugin = ({
rootDir = process.cwd(), rootDir = process.cwd(),
sassOptions = {}, sassOptions = {},
lessOptions = {}, lessOptions = {},
stylusOptions = {} stylusOptions = {},
writeToFile = true
}: PostCSSPluginOptions): Plugin => ({ }: PostCSSPluginOptions): Plugin => ({
name: "postcss2", name: "postcss2",
setup(build) { setup(build) {
@ -152,14 +154,21 @@ const postCSSPlugin = ({
}); });
// Write result CSS // Write result CSS
await writeFile(tmpFilePath, result.css); if (writeToFile) {
await writeFile(tmpFilePath, result.css);
}
return { return {
namespace: isModule ? "postcss-module" : "file", namespace: isModule
? "postcss-module"
: writeToFile
? "file"
: "postcss-text",
path: tmpFilePath, path: tmpFilePath,
watchFiles: getFilesRecursive(sourceDir), watchFiles: getFilesRecursive(sourceDir),
pluginData: { pluginData: {
originalPath: sourceFullPath originalPath: sourceFullPath,
css: result.css
} }
}; };
} }
@ -172,16 +181,30 @@ const postCSSPlugin = ({
const mod = modulesMap.find( const mod = modulesMap.find(
({ path }) => path === args?.pluginData?.originalPath ({ path }) => path === args?.pluginData?.originalPath
), ),
resolveDir = path.dirname(args.path); resolveDir = path.dirname(args.path),
css = args?.pluginData?.css || "";
return { return {
resolveDir, resolveDir,
contents: `import ${JSON.stringify( contents: [
args.path writeToFile ? `import ${JSON.stringify(args.path)};` : null,
)};\nexport default ${JSON.stringify(mod && mod.map ? mod.map : {})};` `export default ${JSON.stringify(mod && mod.map ? mod.map : {})};`,
writeToFile
? null
: `export const stylesheet=${JSON.stringify(css)};`
]
.filter(Boolean)
.join("\n")
}; };
} }
); );
build.onLoad({ filter: /.*/, namespace: "postcss-text" }, async (args) => {
const css = args?.pluginData?.css || "";
return {
contents: `export default ${JSON.stringify(css)};`
};
});
} }
}); });