Skip to content

Commit

Permalink
🏗✨ Add lazy-build support for nested CSS imports (#36742)
Browse files Browse the repository at this point in the history
  • Loading branch information
rsimha committed Nov 3, 2021
1 parent 76380b7 commit 5666379
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 2 deletions.
29 changes: 27 additions & 2 deletions build-system/tasks/css/jsify-css.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
'use strict';

const cssImports = require('css-imports');
const cssnano = require('cssnano');
const fs = require('fs');
const fs = require('fs-extra');
const path = require('path');
const postcss = require('postcss');
const postcssImport = require('postcss-import');
Expand Down Expand Up @@ -99,13 +100,37 @@ async function transformCssString(contents, opt_filename) {
*/
async function jsifyCssAsync(filename) {
const {contents, hash: filehash} = await batchedRead(filename);
const hash = md5(filehash, await getEnvironmentHash());
const imports = await getCssImports(filename);
const importHashes = await Promise.all(
imports.map(async (importedFile) => (await batchedRead(importedFile)).hash)
);
const hash = md5(filehash, ...importHashes, await getEnvironmentHash());
const result = await transformCss(contents, hash, filename);

result.warnings.forEach((warn) => log(red(warn)));
return result.css + '\n/*# sourceURL=/' + filename + '*/';
}

/**
* Computes the transitive closure of CSS files imported by the given file.
* @param {string} cssFile
* @return {Promise<!Array<string>>}
*/
async function getCssImports(cssFile) {
const contents = await fs.readFile(cssFile);
const topLevelImports = cssImports(contents)
.map((result) => result.path)
.filter((importedFile) => !importedFile.startsWith('http'))
.map((importedFile) => path.join(path.dirname(cssFile), importedFile));
if (topLevelImports.length == 0) {
return topLevelImports;
}
const nestedImports = await Promise.all(
topLevelImports.map(async (file) => await getCssImports(file))
);
return topLevelImports.concat(nestedImports).flat();
}

/**
* @param {string} contents
* @param {string} hash
Expand Down
31 changes: 31 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"codecov": "3.8.3",
"commander": "7.2.0",
"connect-header": "0.0.5",
"css-imports": "0.3.1",
"css-selector-tokenizer": "0.8.0",
"css-what": "5.1.0",
"cssnano": "5.0.8",
Expand Down

0 comments on commit 5666379

Please sign in to comment.