diff --git a/src/fixtures/no-declaration-file.css b/src/fixtures/no-declaration-file.css new file mode 100644 index 0000000..07ddce3 --- /dev/null +++ b/src/fixtures/no-declaration-file.css @@ -0,0 +1,9 @@ +html { + box-sizing: border-box; +} + +*, +*:before, +*:after { + box-sizing: inherit; +} diff --git a/src/logic.js b/src/logic.js index 0b02d16..50499aa 100644 --- a/src/logic.js +++ b/src/logic.js @@ -6,9 +6,18 @@ import { parse as parseCss, walk } from "css-tree"; /* globals process -- Node/CLI tool */ +/** + * Generates TypeScript declaration file for the stylesheet file at the given + * `path`. Includes the given `time` in the generated comment. + * + * @param path {string} - Path to stylesheet file. + * @param time {string} - Timestamp string to include in generated comment. + * @returns {Promise} TypeScript declaration file content or + * `undefined` if no declarations to write. + */ export async function generateDeclaration(path, time) { // Handle case where the file got deleted by the time we got here - if (!existsSync(path)) return; + if (!existsSync(path)) return undefined; const css = await readFile(path, `utf8`); @@ -28,7 +37,8 @@ export async function generateDeclaration(path, time) { } }); - return ts; + // Only return TypeScript if we wrote something + return exportedNames.size === 0 ? undefined : ts; } export function dtsPath(path) { diff --git a/src/logic.test.js b/src/logic.test.js index 31e16ba..849f4b4 100644 --- a/src/logic.test.js +++ b/src/logic.test.js @@ -9,11 +9,20 @@ import { dtsPath, generateDeclaration } from "./logic.js"; const __dirname = dirname(fileURLToPath(import.meta.url)); describe(`css-typed`, () => { + it(`should not generate an empty declaration file [#9]`, async () => { + const path = fixtureFile(`no-declaration-file.css`); + expect(await generateDeclaration(path, `$TIME`)).toBeUndefined(); + }); + describe.each([`foo.css`, `foo.module.css`])(`%s`, (filename) => { it(`should match expected output`, async () => { - const path = join(__dirname, `fixtures`, filename); + const path = fixtureFile(filename); const expected = readFileSync(dtsPath(path), { encoding: `utf8` }); expect(await generateDeclaration(path, `$TIME`)).toStrictEqual(expected); }); }); }); + +function fixtureFile(filename) { + return join(__dirname, `fixtures`, filename); +} diff --git a/src/main.js b/src/main.js index e933054..363f3d8 100755 --- a/src/main.js +++ b/src/main.js @@ -35,7 +35,15 @@ async function main(pattern) { process.exit(0); } +/** + * Writes the TypeScript declaration content to file. Handles the output path. + * + * @param path {string} - Path to the original stylesheet file. NOT the path to write. + * @param ts {string | undefined} - The TypeScript declaration content to write. + * @returns {Promise} Empty promise indicating when writing has completed. + */ async function writeDeclarationFile(path, ts) { + if (!ts) return undefined; await writeFile(dtsPath(path), ts, `utf8`); return undefined; }