Home / File/ prebuild.js — astro Source File

prebuild.js — astro Source File

Architecture documentation for prebuild.js, a javascript file in the astro codebase. 6 imports, 1 dependents.

File javascript CoreAstro CoreMiddleware 6 imports 1 dependents 2 functions

Entity Profile

Dependency Diagram

graph LR
  94d4ebd1_5989_8457_de40_0682a9174dd4["prebuild.js"]
  e16a223b_37f3_6b25_1ee1_2b7bcb9d9415["node:fs"]
  94d4ebd1_5989_8457_de40_0682a9174dd4 --> e16a223b_37f3_6b25_1ee1_2b7bcb9d9415
  c52a5f83_66e3_37d7_9ebb_767f7129bc62["node:path"]
  94d4ebd1_5989_8457_de40_0682a9174dd4 --> c52a5f83_66e3_37d7_9ebb_767f7129bc62
  d9a92db9_c95e_9165_13ac_24b3d859d946["node:url"]
  94d4ebd1_5989_8457_de40_0682a9174dd4 --> d9a92db9_c95e_9165_13ac_24b3d859d946
  972c6fe0_4a8d_d55e_c1b0_a57c5bf4ed60["esbuild"]
  94d4ebd1_5989_8457_de40_0682a9174dd4 --> 972c6fe0_4a8d_d55e_c1b0_a57c5bf4ed60
  10250468_0e83_bd69_43e9_3bcef2294a91["piccolore"]
  94d4ebd1_5989_8457_de40_0682a9174dd4 --> 10250468_0e83_bd69_43e9_3bcef2294a91
  e64464d4_88a4_c7e2_f90f_758b06231bbe["tinyglobby"]
  94d4ebd1_5989_8457_de40_0682a9174dd4 --> e64464d4_88a4_c7e2_f90f_758b06231bbe
  35c0b351_a315_b75b_aa2a_7f7a823ba60f["build.js"]
  35c0b351_a315_b75b_aa2a_7f7a823ba60f --> 94d4ebd1_5989_8457_de40_0682a9174dd4
  style 94d4ebd1_5989_8457_de40_0682a9174dd4 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import esbuild from 'esbuild';
import colors from 'piccolore';
import { glob } from 'tinyglobby';

function escapeTemplateLiterals(str) {
	return str.replace(/\`/g, '\\`').replace(/\$\{/g, '\\${');
}

export default async function prebuild(...args) {
	let buildToString = args.indexOf('--to-string');
	if (buildToString !== -1) {
		args.splice(buildToString, 1);
		buildToString = true;
	}
	let minify = true;
	let minifyIdx = args.indexOf('--no-minify');
	if (minifyIdx !== -1) {
		minify = false;
		args.splice(minifyIdx, 1);
	}

	let patterns = args;
	// NOTE: absolute paths returned are forward slashes on windows
	let entryPoints = [].concat(
		...(await Promise.all(
			patterns.map((pattern) => glob(pattern, { onlyFiles: true, absolute: true })),
		)),
	);

	function getPrebuildURL(entryfilepath, dev = false) {
		const entryURL = pathToFileURL(entryfilepath);
		const basename = path.basename(entryfilepath);
		const ext = path.extname(entryfilepath);
		const name = basename.slice(0, basename.indexOf(ext));
		const outname = dev ? `${name}.prebuilt-dev${ext}` : `${name}.prebuilt${ext}`;
		const outURL = new URL('./' + outname, entryURL);
		return outURL;
	}

	async function prebuildFile(filepath) {
		let tscode = await fs.promises.readFile(filepath, 'utf-8');
		// If we're bundling a client directive, modify the code to match `packages/astro/src/core/client-directive/build.ts`.
		// If updating this code, make sure to also update that file.
		if (filepath.includes('runtime/client')) {
			// `export default xxxDirective` is a convention used in the current client directives that we use
			// to make sure we bundle this right. We'll error below if this convention isn't followed.
			const newTscode = tscode.replace(
				/export default (.*?)Directive/,
				(_, name) =>
					`(self.Astro || (self.Astro = {})).${name} = ${name}Directive;window.dispatchEvent(new Event('astro:${name}'))`,
			);
			if (newTscode === tscode) {
				console.error(
					colors.red(
						`${filepath} doesn't follow the \`export default xxxDirective\` convention. The prebuilt output may be wrong. ` +
							`For more information, check out ${fileURLToPath(import.meta.url)}`,
					),
				);
			}
			tscode = newTscode;
		}

		const esbuildOptions = {
			stdin: {
				contents: tscode,
				resolveDir: path.dirname(filepath),
				loader: 'ts',
				sourcefile: filepath,
			},
			format: 'iife',
			target: ['es2018'],
			minify,
			bundle: true,
			write: false,
		};

		const results = await Promise.all(
			[
				{
					build: await esbuild.build(esbuildOptions),
					dev: false,
				},
				filepath.includes('astro-island')
					? {
							build: await esbuild.build({
								...esbuildOptions,
								define: { 'process.env.NODE_ENV': '"development"' },
							}),
							dev: true,
						}
					: undefined,
			].filter((entry) => entry),
		);

		for (const result of results) {
			const code = result.build.outputFiles[0].text.trim();
			const rootURL = new URL('../../', import.meta.url);
			const rel = path.relative(fileURLToPath(rootURL), filepath);
			const generatedCode = escapeTemplateLiterals(code);
			const mod = `/**
 * This file is prebuilt from ${rel}
 * Do not edit this directly, but instead edit that file and rerun the prebuild
 * to generate this file.
 */

export default \`${generatedCode}\`;`;
			const url = getPrebuildURL(filepath, result.dev);
			await fs.promises.writeFile(url, mod, 'utf-8');
		}
	}
	for (const entrypoint of entryPoints) {
		await prebuildFile(entrypoint);
	}
}

Domain

Subdomains

Dependencies

  • esbuild
  • node:fs
  • node:path
  • node:url
  • piccolore
  • tinyglobby

Imported By

Frequently Asked Questions

What does prebuild.js do?
prebuild.js is a source file in the astro codebase, written in javascript. It belongs to the CoreAstro domain, CoreMiddleware subdomain.
What functions are defined in prebuild.js?
prebuild.js defines 2 function(s): escapeTemplateLiterals, prebuild.
What does prebuild.js depend on?
prebuild.js imports 6 module(s): esbuild, node:fs, node:path, node:url, piccolore, tinyglobby.
What files import prebuild.js?
prebuild.js is imported by 1 file(s): build.js.
Where is prebuild.js in the architecture?
prebuild.js is located at scripts/cmd/prebuild.js (domain: CoreAstro, subdomain: CoreMiddleware, directory: scripts/cmd).

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free