({file, preloadCSS, target, rootDir})
| 29 | const CONCURRENT_WORKERS = require('os').cpus().length; |
| 30 | |
| 31 | async function optimizeFile({file, preloadCSS, target, rootDir}) { |
| 32 | const baseExt = path.extname(file).toLowerCase(); |
| 33 | |
| 34 | // TODO: add debug in plugins? |
| 35 | // log(`optimizing ${projectURL(file, rootDir)}…`, 'debug'); |
| 36 | |
| 37 | // optimize based on extension. if it’s not here, leave as-is |
| 38 | switch (baseExt) { |
| 39 | case '.css': { |
| 40 | const shouldOptimize = options.minifyCSS; |
| 41 | if (!shouldOptimize) return; |
| 42 | |
| 43 | // minify |
| 44 | let code = fs.readFileSync(file, 'utf-8'); |
| 45 | code = csso.minify(code).css; |
| 46 | fs.writeFileSync(file, code, 'utf-8'); |
| 47 | break; |
| 48 | } |
| 49 | case '.js': |
| 50 | case '.mjs': { |
| 51 | const shouldOptimize = options.preloadCSS || options.minifyJS; |
| 52 | if (!shouldOptimize) return; |
| 53 | |
| 54 | let code = fs.readFileSync(file, 'utf-8'); |
| 55 | |
| 56 | // embed CSS |
| 57 | if (preloadCSS) { |
| 58 | code = transformCSSProxy(file, code); |
| 59 | } |
| 60 | |
| 61 | // minify if enabled |
| 62 | if (options.minifyJS) { |
| 63 | const minified = await esbuild.transform(code, { |
| 64 | minify: true, |
| 65 | charset: 'utf8', |
| 66 | target, |
| 67 | }); |
| 68 | code = minified.code; |
| 69 | fs.writeFileSync(file, code); |
| 70 | } |
| 71 | |
| 72 | fs.writeFileSync(file, code); |
| 73 | break; |
| 74 | } |
| 75 | case '.html': { |
| 76 | const shouldOptimize = options.preloadCSS || options.preloadModules || options.minifyHTML; |
| 77 | if (!shouldOptimize) return; |
| 78 | |
| 79 | let code = fs.readFileSync(file, 'utf-8'); |
| 80 | |
| 81 | // preload CSS |
| 82 | if (preloadCSS) { |
| 83 | code = injectHTML(code, { |
| 84 | headEnd: `<link rel="stylesheet" href="${options.preloadCSSFileName}" />\n`, |
| 85 | }); |
| 86 | } |
| 87 | |
| 88 | // preload JS |
no test coverage detected