Compare commits

..

1 Commits

Author SHA1 Message Date
Suraj Shetty
fb0d9eac15
fix(sass): Watch included files as well 2022-03-14 14:51:14 +05:30
8 changed files with 31 additions and 211 deletions

View File

@ -25,7 +25,7 @@ const postCssPlugin = require("esbuild-plugin-postcss2");
esbuild.build({ esbuild.build({
... ...
plugins: [ plugins: [
postCssPlugin.default() postCssPlugin()
] ]
... ...
}); });
@ -41,7 +41,7 @@ const autoprefixer = require("autoprefixer");
esbuild.build({ esbuild.build({
... ...
plugins: [ plugins: [
postCssPlugin.default({ postCssPlugin({
plugins: [autoprefixer] plugins: [autoprefixer]
}) })
] ]
@ -54,7 +54,7 @@ esbuild.build({
PostCSS modules are enabled by default. You can pass in a config or disable it with the `modules` field: PostCSS modules are enabled by default. You can pass in a config or disable it with the `modules` field:
```js ```js
postCssPlugin.default({ postCssPlugin({
// pass in `postcss-modules` custom options // pass in `postcss-modules` custom options
// set to false to disable // set to false to disable
modules: { modules: {
@ -69,17 +69,6 @@ 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 ### Preprocessors
To use preprocessors (`sass`, `scss`, `stylus`, `less`), just add the desired preprocessor as a `devDependency`: To use preprocessors (`sass`, `scss`, `stylus`, `less`), just add the desired preprocessor as a `devDependency`:

View File

@ -1,11 +1,8 @@
{ {
"name": "@frappe/esbuild-plugin-postcss2", "name": "esbuild-plugin-postcss2",
"version": "0.1.3", "version": "0.0.9",
"description": "Use postcss with esbuild", "description": "Use postcss with esbuild",
"repository": { "repository": "https://github.com/martonlederer/esbuild-plugin-postcss2",
"type": "git",
"url": "git+https://github.com/frappe/esbuild-plugin-postcss2.git"
},
"author": "Marton Lederer <marton@lederer.hu>", "author": "Marton Lederer <marton@lederer.hu>",
"license": "MIT", "license": "MIT",
"private": false, "private": false,
@ -33,6 +30,7 @@
"autoprefixer": "^10.2.5", "autoprefixer": "^10.2.5",
"fs-extra": "^9.1.0", "fs-extra": "^9.1.0",
"less": "^4.x", "less": "^4.x",
"postcss": "8.x",
"postcss-modules": "^4.0.0", "postcss-modules": "^4.0.0",
"resolve-file": "^0.3.0", "resolve-file": "^0.3.0",
"sass": "^1.x", "sass": "^1.x",
@ -53,7 +51,6 @@
"esbuild": "^0.11.2", "esbuild": "^0.11.2",
"mocha": "^8.3.2", "mocha": "^8.3.2",
"normalize.css": "^8.0.1", "normalize.css": "^8.0.1",
"postcss-import": "^14.0.2",
"prettier": "^2.2.1", "prettier": "^2.2.1",
"typescript": "^4.2.3", "typescript": "^4.2.3",
"yorkie": "^2.0.0" "yorkie": "^2.0.0"
@ -63,9 +60,5 @@
"postcss": "8.x", "postcss": "8.x",
"sass": "^1.x", "sass": "^1.x",
"stylus": "^0.x" "stylus": "^0.x"
}, }
"bugs": {
"url": "https://github.com/frappe/esbuild-plugin-postcss2/issues"
},
"homepage": "https://github.com/frappe/esbuild-plugin-postcss2#readme"
} }

View File

@ -1,12 +1,6 @@
import { Plugin } from "esbuild"; import { Plugin } from "esbuild";
import { Plugin as PostCSSPlugin, Message } from "postcss"; import { Plugin as PostCSSPlugin } from "postcss";
import { import { ensureDir, readFile, writeFile } from "fs-extra";
ensureDir,
readFile,
readdirSync,
statSync,
writeFile
} from "fs-extra";
import { TextDecoder } from "util"; import { TextDecoder } from "util";
import { import {
SassException, SassException,
@ -30,7 +24,6 @@ interface PostCSSPluginOptions {
sassOptions?: SassOptions; sassOptions?: SassOptions;
lessOptions?: Less.Options; lessOptions?: Less.Options;
stylusOptions?: StylusRenderOptions; stylusOptions?: StylusRenderOptions;
fileIsModule?: (filename: string) => boolean;
} }
interface CSSModule { interface CSSModule {
@ -40,25 +33,14 @@ interface CSSModule {
}; };
} }
export const defaultOptions: PostCSSPluginOptions = {
plugins: [],
modules: true,
rootDir: process.cwd(),
sassOptions: {},
lessOptions: {},
stylusOptions: {},
fileIsModule: null
};
const postCSSPlugin = ({ const postCSSPlugin = ({
plugins = [], plugins = [],
modules = true, modules = true,
rootDir = process.cwd(), rootDir = process.cwd(),
sassOptions = {}, sassOptions = {},
lessOptions = {}, lessOptions = {},
stylusOptions = {}, stylusOptions = {}
fileIsModule }: PostCSSPluginOptions): Plugin => ({
}: PostCSSPluginOptions = defaultOptions): Plugin => ({
name: "postcss2", name: "postcss2",
setup(build) { setup(build) {
// get a temporary path where we can save compiled CSS // get a temporary path where we can save compiled CSS
@ -101,52 +83,31 @@ const postCSSPlugin = ({
const sourceExt = path.extname(sourceFullPath); const sourceExt = path.extname(sourceFullPath);
const sourceBaseName = path.basename(sourceFullPath, sourceExt); const sourceBaseName = path.basename(sourceFullPath, sourceExt);
const isModule = fileIsModule
? fileIsModule(sourceFullPath)
: sourceBaseName.match(/\.module$/);
const sourceDir = path.dirname(sourceFullPath); const sourceDir = path.dirname(sourceFullPath);
const sourceRelDir = path.relative(path.dirname(rootDir), sourceDir);
const isModule = sourceBaseName.match(/\.module$/);
const tmpDir = path.resolve(tmpDirPath, sourceRelDir);
const watchFiles = [sourceFullPath]; const watchFiles = [sourceFullPath];
let tmpFilePath: string; let tmpFilePath = path.resolve(
if (args.kind === "entry-point") { tmpDir,
// For entry points, we use <tempdir>/<path-within-project-root>/<file-name>.css `${Date.now()}-${sourceBaseName}.css`
const sourceRelDir = path.relative(
path.dirname(rootDir),
path.dirname(sourceFullPath)
); );
tmpFilePath = path.resolve(
tmpDirPath, // When CSS is an entry-point we don't want to append Date.now()
sourceRelDir, if (args.kind === "entry-point")
`${sourceBaseName}.css` tmpFilePath = path.resolve(tmpDir, `${sourceBaseName}.css`);
);
await ensureDir(path.dirname(tmpFilePath)); await ensureDir(tmpDir);
} else {
// For others, we use <tempdir>/<unique-directory-name>/<file-name>.css
//
// This is a workaround for the following esbuild issue:
// https://github.com/evanw/esbuild/issues/1101
//
// esbuild is unable to find the file, even though it does exist. This only
// happens for files in a directory with several other entries, so by
// creating a unique directory name per file on every build, we guarantee
// that there will only every be a single file present within the directory,
// circumventing the esbuild issue.
const uniqueTmpDir = path.resolve(tmpDirPath, uniqueId());
tmpFilePath = path.resolve(uniqueTmpDir, `${sourceBaseName}.css`);
}
await ensureDir(path.dirname(tmpFilePath));
const fileContent = await readFile(sourceFullPath); const fileContent = await readFile(sourceFullPath);
let css = sourceExt === ".css" ? fileContent : ""; let css = sourceExt === ".css" ? fileContent : "";
// parse files with preprocessors // parse files with preprocessors
if (sourceExt === ".sass" || sourceExt === ".scss") { if (sourceExt === ".sass" || sourceExt === ".scss") {
const sassResult = await renderSass({ let result = await renderSass({ ...sassOptions, file: sourceFullPath })
...sassOptions, css = result.css.toString();
file: sourceFullPath watchFiles.push(...result.stats.includedFiles);
});
css = sassResult.css.toString();
watchFiles.push(...sassResult.stats.includedFiles);
} }
if (sourceExt === ".styl") if (sourceExt === ".styl")
css = await renderStylus(new TextDecoder().decode(fileContent), { css = await renderStylus(new TextDecoder().decode(fileContent), {
@ -169,7 +130,6 @@ const postCSSPlugin = ({
from: sourceFullPath, from: sourceFullPath,
to: tmpFilePath to: tmpFilePath
}); });
watchFiles.push(...getPostCssDependencies(result.messages));
// Write result CSS // Write result CSS
await writeFile(tmpFilePath, result.css); await writeFile(tmpFilePath, result.css);
@ -241,35 +201,4 @@ function getSassImpl() {
return require(impl); return require(impl);
} }
function getFilesRecursive(directory: string): string[] {
return readdirSync(directory).reduce((files, file) => {
const name = path.join(directory, file);
return statSync(name).isDirectory()
? [...files, ...getFilesRecursive(name)]
: [...files, name];
}, []);
}
let idCounter = 0;
/**
* Generates an id that is guaranteed to be unique for the Node.JS instance.
*/
function uniqueId(): string {
return Date.now().toString(16) + (idCounter++).toString(16);
}
function getPostCssDependencies(messages: Message[]): string[] {
let dependencies = [];
for (const message of messages) {
if (message.type == "dir-dependency") {
dependencies.push(...getFilesRecursive(message.dir));
} else if (message.type == "dependency") {
dependencies.push(message.file);
}
}
return dependencies;
}
export default postCSSPlugin; export default postCSSPlugin;

View File

@ -1,5 +1,4 @@
const autoprefixer = require("autoprefixer"), const autoprefixer = require("autoprefixer"),
postCssImport = require("postcss-import"),
{ build } = require("esbuild"), { build } = require("esbuild"),
postCSS = require("../dist"), postCSS = require("../dist"),
{ assert } = require("chai"), { assert } = require("chai"),
@ -46,7 +45,7 @@ describe("PostCSS esbuild tests", () => {
}) })
.catch(done); .catch(done);
}); });
it("Works while waching css files directly", (done) => { it("Works while waching css files", (done) => {
let notTriggerTimeout = null; let notTriggerTimeout = null;
build({ build({
entryPoints: ["tests/watch.ts"], entryPoints: ["tests/watch.ts"],
@ -78,66 +77,6 @@ describe("PostCSS esbuild tests", () => {
}) })
.catch(() => process.exit(1)); .catch(() => process.exit(1));
}); });
it("Works while waching css files through dependencies", (done) => {
let notTriggerTimeout = null;
build({
entryPoints: ["tests/watch2.ts"],
bundle: true,
outdir: "dist",
watch: {
onRebuild: (error, result) => {
notTriggerTimeout = null;
if (error) return done(error);
assert(result);
done();
}
},
plugins: [
postCSS.default({
plugins: [autoprefixer, postCssImport]
})
]
})
.then(() => {
// test if modifying the css actually triggers the onRebuild event
const data = `.Test { display: block; }`;
fs.writeFile("./styles/watch3.css", data, (err) => {
if (err) return done(err);
notTriggerTimeout = setTimeout(() => {
done("Watch file not triggered!");
}, 1000);
});
})
.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) { function test(entryPoint) {

View File

@ -1,5 +0,0 @@
@import "./watch3.css";
.Test {
display: block;
}

View File

@ -1,3 +0,0 @@
.Test {
display: block;
}

View File

@ -1 +0,0 @@
import "../styles/watch2.css";

View File

@ -1002,25 +1002,11 @@ picomatch@^2.0.4, picomatch@^2.2.1:
resolved "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz" resolved "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz"
integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==
pify@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c"
integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw=
pify@^4.0.1: pify@^4.0.1:
version "4.0.1" version "4.0.1"
resolved "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz" resolved "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz"
integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==
postcss-import@^14.0.2:
version "14.0.2"
resolved "https://registry.yarnpkg.com/postcss-import/-/postcss-import-14.0.2.tgz#60eff77e6be92e7b67fe469ec797d9424cae1aa1"
integrity sha512-BJ2pVK4KhUyMcqjuKs9RijV5tatNzNa73e/32aBVE/ejYPe37iH+6vAu9WvqUkB5OAYgLHzbSvzHnorybJCm9g==
dependencies:
postcss-value-parser "^4.0.0"
read-cache "^1.0.0"
resolve "^1.1.7"
postcss-modules-extract-imports@^3.0.0: postcss-modules-extract-imports@^3.0.0:
version "3.0.0" version "3.0.0"
resolved "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.0.0.tgz" resolved "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.0.0.tgz"
@ -1073,7 +1059,7 @@ postcss-selector-parser@^6.0.2, postcss-selector-parser@^6.0.4:
uniq "^1.0.1" uniq "^1.0.1"
util-deprecate "^1.0.2" util-deprecate "^1.0.2"
postcss-value-parser@^4.0.0, postcss-value-parser@^4.1.0: postcss-value-parser@^4.1.0:
version "4.1.0" version "4.1.0"
resolved "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.1.0.tgz" resolved "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.1.0.tgz"
integrity sha512-97DXOFbQJhk71ne5/Mt6cOu6yxsSfM0QGQyl0L25Gca4yGWEGJaig7l7gbCX623VqTBNGLRLaVUCnNkcedlRSQ== integrity sha512-97DXOFbQJhk71ne5/Mt6cOu6yxsSfM0QGQyl0L25Gca4yGWEGJaig7l7gbCX623VqTBNGLRLaVUCnNkcedlRSQ==
@ -1109,13 +1095,6 @@ randombytes@^2.1.0:
dependencies: dependencies:
safe-buffer "^5.1.0" safe-buffer "^5.1.0"
read-cache@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/read-cache/-/read-cache-1.0.0.tgz#e664ef31161166c9751cdbe8dbcf86b5fb58f774"
integrity sha1-5mTvMRYRZsl1HNvo28+GtftY93Q=
dependencies:
pify "^2.3.0"
readdirp@~3.5.0: readdirp@~3.5.0:
version "3.5.0" version "3.5.0"
resolved "https://registry.npmjs.org/readdirp/-/readdirp-3.5.0.tgz" resolved "https://registry.npmjs.org/readdirp/-/readdirp-3.5.0.tgz"
@ -1154,7 +1133,7 @@ resolve-url@^0.2.1:
resolved "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz" resolved "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz"
integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=
resolve@^1.1.7, resolve@^1.2.0: resolve@^1.2.0:
version "1.20.0" version "1.20.0"
resolved "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz" resolved "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz"
integrity sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A== integrity sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==