Scan HTML for static imports
(htmlFiles, buildDirectory)
| 10 | |
| 11 | /** Scan HTML for static imports */ |
| 12 | async function scanHTML(htmlFiles, buildDirectory) { |
| 13 | const importList = {}; |
| 14 | await Promise.all( |
| 15 | htmlFiles.map(async (htmlFile) => { |
| 16 | // TODO: add debug in plugins? |
| 17 | // log(`scanning ${projectURL(file, buildDirectory)} for imports`, 'debug'); |
| 18 | |
| 19 | const allCSSImports = new Set(); // all CSS imports for this HTML file |
| 20 | const allJSImports = new Set(); // all JS imports for this HTML file |
| 21 | const entry = new Set(); // keep track of HTML entry files |
| 22 | |
| 23 | const code = await fs.promises.readFile(htmlFile, 'utf-8'); |
| 24 | |
| 25 | // <link> |
| 26 | hypertag(code, 'link').forEach((link) => { |
| 27 | if (!link.href) return; |
| 28 | if (isRemoteModule(link.href)) { |
| 29 | allCSSImports.add(link.href); |
| 30 | } else { |
| 31 | const resolvedCSS = |
| 32 | link.href[0] === '/' |
| 33 | ? path.join(buildDirectory, link.href) |
| 34 | : path.join(path.dirname(htmlFile), link.href); |
| 35 | allCSSImports.add(resolvedCSS); |
| 36 | } |
| 37 | }); |
| 38 | |
| 39 | // <script> |
| 40 | hypertag(code, 'script').forEach((script) => { |
| 41 | if (!script.src) return; |
| 42 | if (isRemoteModule(script.src)) { |
| 43 | allJSImports.add(script.src); |
| 44 | } else { |
| 45 | const resolvedJS = |
| 46 | script.src[0] === '/' |
| 47 | ? path.join(buildDirectory, script.src) |
| 48 | : path.join(path.dirname(htmlFile), script.src); |
| 49 | allJSImports.add(resolvedJS); |
| 50 | entry.add(resolvedJS); |
| 51 | } |
| 52 | }); |
| 53 | |
| 54 | // traverse all JS for other static imports (scannedFiles keeps track of files so we never redo work) |
| 55 | const scannedFiles = new Set(); |
| 56 | allJSImports.forEach((jsFile) => { |
| 57 | scanJS({ |
| 58 | file: jsFile, |
| 59 | rootDir: buildDirectory, |
| 60 | scannedFiles, |
| 61 | importList: allJSImports, |
| 62 | }).forEach((i) => allJSImports.add(i)); |
| 63 | }); |
| 64 | |
| 65 | // return |
| 66 | importList[htmlFile] = { |
| 67 | entry: Array.from(entry), |
| 68 | css: Array.from(allCSSImports), |
| 69 | js: Array.from(allJSImports), |
no test coverage detected