Skip to content

Commit

Permalink
Fix format
Browse files Browse the repository at this point in the history
  • Loading branch information
edoardocavazza committed Nov 4, 2024
1 parent 475a487 commit 595b399
Show file tree
Hide file tree
Showing 2 changed files with 179 additions and 164 deletions.
18 changes: 10 additions & 8 deletions docs/guide/esbuild-plugin-html.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,14 +303,16 @@ await esbuild.build({
outdir: 'public',
assetNames: 'assets/[name]-[hash]',
chunkNames: '[ext]/[name]-[hash]',
plugins: [htmlPlugin({
extensions: ['.html', '.hbs'],
preprocess: async (html, path) => {
const { compile } = await import('handlebars');
const template = compile(contents);
return template({});
},
})],
plugins: [
htmlPlugin({
extensions: ['.html', '.hbs'],
preprocess: async (html, path) => {
const { compile } = await import('handlebars');
const template = compile(contents);
return template({});
},
}),
],
});
```

Expand Down
325 changes: 169 additions & 156 deletions packages/esbuild-plugin-html/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,13 @@ export default function ({
const buffer = resultOutputFile
? Buffer.from(resultOutputFile.contents)
: await readFile(actualOutputFile);
const finalOutputFile = build.resolveOutputFile(path.join(path.dirname(mainInput), `${path.basename(mainInput, path.extname(mainInput))}.html`), buffer);
const finalOutputFile = build.resolveOutputFile(
path.join(
path.dirname(mainInput),
`${path.basename(mainInput, path.extname(mainInput))}.html`
),
buffer
);

delete outputs[outputFile];
outputs[build.getOutputName(finalOutputFile)] = output;
Expand All @@ -176,165 +182,172 @@ export default function ({
);
});

build.onTransform({
filter: new RegExp(`(${(extensions.map((ext) => {
if (ext[0] !== '.') {
ext = `\\.${ext}`;
}
return `\\${ext}`;
}).join('|'))})$`)
}, async (args) => {
entryPoints.push(args.path);

const [
{ collectStyles },
{ collectScripts },
{ collectAssets },
{ collectWebManifest },
{ collectIcons },
{ collectScreens },
] = await Promise.all([
import('./collectStyles.js'),
import('./collectScripts.js'),
import('./collectAssets.js'),
import('./collectWebManifest.js'),
import('./collectIcons.js'),
import('./collectScreens.js'),
]);

const code = await preprocess(args.code, args.path);
const $ = loadHtml(code);
const root = $.root();
let count = 0;

/**
* @param {string} file
*/
const resolveFile = (file) =>
build.resolve(`./${file}`, {
kind: 'dynamic-import',
importer: args.path,
resolveDir: path.dirname(args.path),
pluginData: null,
namespace: 'file',
});

/**
* @param {string} path
* @param {Partial<import('esbuild').OnLoadArgs>} [options]
*/
const loadFile = (path, options = {}) =>
build.load({
pluginData: null,
namespace: 'file',
suffix: '',
...options,
path,
with: {},
});

const collectOptions = {
sourceDir: path.dirname(args.path),
workingDir,
outDir: /** @type {string} */ (build.getFullOutDir()),
entryDir: build.resolveOutputDir(args.path),
target: [scriptsTarget, modulesTarget],
};

/**
* Get entry name.
*
* @param {string} ext
* @param {string|undefined} suggestion
* @returns {string}
*/
const createEntry = (ext, suggestion) => {
const i = ++count;

return `${suggestion ? `${suggestion}${i}` : i}.${ext}`;
};

/**
* @type {Helpers}
*/
const helpers = {
createEntry,
resolveAssetFile(source, buffer) {
return build.resolveOutputFile(source, buffer || Buffer.from(''), Build.ASSET);
},
emitFile: build.emitFile.bind(build),
emitChunk: build.emitChunk.bind(build),
emitBuild: build.emitBuild.bind(build),
resolveRelativePath: build.resolveRelativePath.bind(build),
resolve: resolveFile,
load: loadFile,
};

const results = await collectWebManifest($, root, collectOptions, helpers);
results.push(...(await collectScreens($, root, collectOptions, helpers)));
results.push(...(await collectIcons($, root, collectOptions, helpers)));
results.push(...(await collectAssets($, root, collectOptions, helpers)));
results.push(...(await collectStyles($, root, collectOptions, helpers)));
results.push(
...(await collectScripts(
$,
root,
{
...collectOptions,
injectStylesAs,
},
helpers
))
);
build.onTransform(
{
filter: new RegExp(
`(${extensions
.map((ext) => {
if (ext[0] !== '.') {
ext = `\\.${ext}`;
}
return `\\${ext}`;
})
.join('|')})$`
),
},
async (args) => {
entryPoints.push(args.path);

const [
{ collectStyles },
{ collectScripts },
{ collectAssets },
{ collectWebManifest },
{ collectIcons },
{ collectScreens },
] = await Promise.all([
import('./collectStyles.js'),
import('./collectScripts.js'),
import('./collectAssets.js'),
import('./collectWebManifest.js'),
import('./collectIcons.js'),
import('./collectScreens.js'),
]);

const code = await preprocess(args.code, args.path);
const $ = loadHtml(code);
const root = $.root();
let count = 0;

/**
* @param {string} file
*/
const resolveFile = (file) =>
build.resolve(`./${file}`, {
kind: 'dynamic-import',
importer: args.path,
resolveDir: path.dirname(args.path),
pluginData: null,
namespace: 'file',
});

let resultHtml = $.html().replace(/\n\s*$/gm, '');
if (minify) {
await import('htmlnano')
.then(async ({ default: htmlnano }) => {
resultHtml = (
await htmlnano.process(resultHtml, {
minifyJs: false,
minifyCss: false,
minifyJson: false,
...minifyOptions,
})
).html;
})
.catch(() => {
warnings.push({
id: 'missing-htmlnano',
pluginName: 'html',
text: `Unable to load "htmlnano" module for HTML minification.`,
location: null,
notes: [],
detail: '',
});
/**
* @param {string} path
* @param {Partial<import('esbuild').OnLoadArgs>} [options]
*/
const loadFile = (path, options = {}) =>
build.load({
pluginData: null,
namespace: 'file',
suffix: '',
...options,
path,
with: {},
});
} else {
resultHtml = beautify.html(resultHtml);
}

return {
code: resultHtml,
loader: 'file',
watchFiles: results.reduce((acc, result) => {
if (!result) {
const collectOptions = {
sourceDir: path.dirname(args.path),
workingDir,
outDir: /** @type {string} */ (build.getFullOutDir()),
entryDir: build.resolveOutputDir(args.path),
target: [scriptsTarget, modulesTarget],
};

/**
* Get entry name.
*
* @param {string} ext
* @param {string|undefined} suggestion
* @returns {string}
*/
const createEntry = (ext, suggestion) => {
const i = ++count;

return `${suggestion ? `${suggestion}${i}` : i}.${ext}`;
};

/**
* @type {Helpers}
*/
const helpers = {
createEntry,
resolveAssetFile(source, buffer) {
return build.resolveOutputFile(source, buffer || Buffer.from(''), Build.ASSET);
},
emitFile: build.emitFile.bind(build),
emitChunk: build.emitChunk.bind(build),
emitBuild: build.emitBuild.bind(build),
resolveRelativePath: build.resolveRelativePath.bind(build),
resolve: resolveFile,
load: loadFile,
};

const results = await collectWebManifest($, root, collectOptions, helpers);
results.push(...(await collectScreens($, root, collectOptions, helpers)));
results.push(...(await collectIcons($, root, collectOptions, helpers)));
results.push(...(await collectAssets($, root, collectOptions, helpers)));
results.push(...(await collectStyles($, root, collectOptions, helpers)));
results.push(
...(await collectScripts(
$,
root,
{
...collectOptions,
injectStylesAs,
},
helpers
))
);

let resultHtml = $.html().replace(/\n\s*$/gm, '');
if (minify) {
await import('htmlnano')
.then(async ({ default: htmlnano }) => {
resultHtml = (
await htmlnano.process(resultHtml, {
minifyJs: false,
minifyCss: false,
minifyJson: false,
...minifyOptions,
})
).html;
})
.catch(() => {
warnings.push({
id: 'missing-htmlnano',
pluginName: 'html',
text: `Unable to load "htmlnano" module for HTML minification.`,
location: null,
notes: [],
detail: '',
});
});
} else {
resultHtml = beautify.html(resultHtml);
}

return {
code: resultHtml,
loader: 'file',
watchFiles: results.reduce((acc, result) => {
if (!result) {
return acc;
}
if (result.watchFiles) {
return [...acc, ...result.watchFiles];
}
if (result.metafile) {
return [
...acc,
...Object.keys(result.metafile.inputs).map((key) => path.resolve(cwd, key)),
];
}
return acc;
}
if (result.watchFiles) {
return [...acc, ...result.watchFiles];
}
if (result.metafile) {
return [
...acc,
...Object.keys(result.metafile.inputs).map((key) => path.resolve(cwd, key)),
];
}
return acc;
}, /** @type {string[]} */ ([])),
warnings,
};
});
}, /** @type {string[]} */ ([])),
warnings,
};
}
);
},
};

Expand Down

0 comments on commit 595b399

Please sign in to comment.