Refactor and remove esbuild dependency (#5533)

This commit is contained in:
Bjorn Lu 2022-12-06 17:00:36 +08:00 committed by GitHub
parent efc4363e0b
commit 58188e0536
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 43 additions and 43 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Refactor and remove esbuild dependency

View file

@ -124,7 +124,6 @@
"deepmerge-ts": "^4.2.2", "deepmerge-ts": "^4.2.2",
"diff": "^5.1.0", "diff": "^5.1.0",
"es-module-lexer": "^0.10.5", "es-module-lexer": "^0.10.5",
"esbuild": "^0.14.43",
"execa": "^6.1.0", "execa": "^6.1.0",
"fast-glob": "^3.2.11", "fast-glob": "^3.2.11",
"github-slugger": "^1.4.0", "github-slugger": "^1.4.0",
@ -157,7 +156,7 @@
"typescript": "*", "typescript": "*",
"unist-util-visit": "^4.1.0", "unist-util-visit": "^4.1.0",
"vfile": "^5.3.2", "vfile": "^5.3.2",
"vite": "~3.2.4", "vite": "~3.2.5",
"vitefu": "^0.2.1", "vitefu": "^0.2.1",
"yargs-parser": "^21.0.1", "yargs-parser": "^21.0.1",
"zod": "^3.17.3" "zod": "^3.17.3"

View file

@ -2,8 +2,7 @@ import type { GetModuleInfo } from 'rollup';
import type { BuildInternals } from './internal'; import type { BuildInternals } from './internal';
import type { PageBuildData, StaticBuildOptions } from './types'; import type { PageBuildData, StaticBuildOptions } from './types';
import esbuild from 'esbuild'; import { Plugin as VitePlugin, ResolvedConfig, transformWithEsbuild } from 'vite';
import { Plugin as VitePlugin, ResolvedConfig } from 'vite';
import { isCSSRequest } from '../render/util.js'; import { isCSSRequest } from '../render/util.js';
import * as assetName from './css-asset-name.js'; import * as assetName from './css-asset-name.js';
@ -207,11 +206,16 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[]
if (output.name?.endsWith('.css') && typeof output.source === 'string') { if (output.name?.endsWith('.css') && typeof output.source === 'string') {
const cssTarget = settings.config.vite.build?.cssTarget; const cssTarget = settings.config.vite.build?.cssTarget;
const minify = settings.config.vite.build?.minify !== false; const minify = settings.config.vite.build?.minify !== false;
const { code: minifiedCSS } = await esbuild.transform(output.source, { const { code: minifiedCSS } = await transformWithEsbuild(
loader: 'css', output.source,
minify, output.name,
...(cssTarget ? { target: cssTarget } : {}), {
}); loader: 'css',
minify,
target: cssTarget || undefined,
sourcemap: false,
}
);
output.source = minifiedCSS; output.source = minifiedCSS;
} }
} }

View file

@ -1,13 +1,15 @@
import type { BuildResult } from 'esbuild';
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import stripAnsi from 'strip-ansi'; import stripAnsi from 'strip-ansi';
import type { ESBuildTransformResult } from 'vite';
import type { SSRError } from '../../../@types/astro.js'; import type { SSRError } from '../../../@types/astro.js';
import { AggregateError, ErrorWithMetadata } from '../errors.js'; import { AggregateError, ErrorWithMetadata } from '../errors.js';
import { codeFrame } from '../printer.js'; import { codeFrame } from '../printer.js';
import { normalizeLF } from '../utils.js'; import { normalizeLF } from '../utils.js';
type EsbuildMessage = ESBuildTransformResult['warnings'][number];
export const incompatiblePackages = { export const incompatiblePackages = {
'react-spectrum': `@adobe/react-spectrum is not compatible with Vite's server-side rendering mode at the moment. You can still use React Spectrum from the client. Create an island React component and use the client:only directive. From there you can use React Spectrum.`, 'react-spectrum': `@adobe/react-spectrum is not compatible with Vite's server-side rendering mode at the moment. You can still use React Spectrum from the client. Create an island React component and use the client:only directive. From there you can use React Spectrum.`,
}; };
@ -44,7 +46,7 @@ export function collectErrorMetadata(e: any, rootFolder?: URL | undefined): Erro
// If we received an array of errors and it's not from us, it should be from ESBuild, try to extract info for Vite to display // If we received an array of errors and it's not from us, it should be from ESBuild, try to extract info for Vite to display
if (!AggregateError.is(e) && Array.isArray((e as any).errors)) { if (!AggregateError.is(e) && Array.isArray((e as any).errors)) {
(e as BuildResult).errors.forEach((buildError, i) => { (e.errors as EsbuildMessage[]).forEach((buildError, i) => {
const { location, pluginName, text } = buildError; const { location, pluginName, text } = buildError;
// ESBuild can give us a slightly better error message than the one in the error, so let's use it // ESBuild can give us a slightly better error message than the one in the error, so let's use it

View file

@ -1,11 +1,10 @@
import type { TransformResult } from 'rollup'; import type { TransformResult } from 'rollup';
import type { Plugin, ResolvedConfig } from 'vite'; import { EsbuildTransformOptions, Plugin, ResolvedConfig, transformWithEsbuild } from 'vite';
import type { AstroRenderer, AstroSettings } from '../@types/astro'; import type { AstroRenderer, AstroSettings } from '../@types/astro';
import type { LogOptions } from '../core/logger/core.js'; import type { LogOptions } from '../core/logger/core.js';
import type { PluginMetadata } from '../vite-plugin-astro/types'; import type { PluginMetadata } from '../vite-plugin-astro/types';
import babel from '@babel/core'; import babel from '@babel/core';
import esbuild from 'esbuild';
import * as colors from 'kleur/colors'; import * as colors from 'kleur/colors';
import path from 'path'; import path from 'path';
import { error } from '../core/logger/core.js'; import { error } from '../core/logger/core.js';
@ -21,12 +20,10 @@ const IMPORT_STATEMENTS: Record<string, string> = {
astro: "import 'astro/jsx-runtime'", astro: "import 'astro/jsx-runtime'",
}; };
// A fast check regex for the import keyword. False positives are okay. function getEsbuildLoader(filePath: string): EsbuildTransformOptions['loader'] {
const IMPORT_KEYWORD_REGEX = /import/; const fileExt = path.extname(filePath);
function getEsbuildLoader(fileExt: string): string {
if (fileExt === '.mdx') return 'jsx'; if (fileExt === '.mdx') return 'jsx';
return fileExt.slice(1); return fileExt.slice(1) as EsbuildTransformOptions['loader'];
} }
function collectJSXRenderers(renderers: AstroRenderer[]): Map<string, AstroRenderer> { function collectJSXRenderers(renderers: AstroRenderer[]): Map<string, AstroRenderer> {
@ -139,10 +136,9 @@ export default function jsx({ settings, logging }: AstroPluginJSXOptions): Plugi
const { mode } = viteConfig; const { mode } = viteConfig;
// Shortcut: only use Astro renderer for MD and MDX files // Shortcut: only use Astro renderer for MD and MDX files
if (id.endsWith('.mdx')) { if (id.endsWith('.mdx')) {
const { code: jsxCode } = await esbuild.transform(code, { const { code: jsxCode } = await transformWithEsbuild(code, id, {
loader: getEsbuildLoader(path.extname(id)) as esbuild.Loader, loader: getEsbuildLoader(id),
jsx: 'preserve', jsx: 'preserve',
sourcefile: id,
sourcemap: 'inline', sourcemap: 'inline',
}); });
return transformJSX({ return transformJSX({
@ -156,10 +152,9 @@ export default function jsx({ settings, logging }: AstroPluginJSXOptions): Plugi
} }
if (defaultJSXRendererEntry && jsxRenderersIntegrationOnly.size === 1) { if (defaultJSXRendererEntry && jsxRenderersIntegrationOnly.size === 1) {
// downlevel any non-standard syntax, but preserve JSX // downlevel any non-standard syntax, but preserve JSX
const { code: jsxCode } = await esbuild.transform(code, { const { code: jsxCode } = await transformWithEsbuild(code, id, {
loader: getEsbuildLoader(path.extname(id)) as esbuild.Loader, loader: getEsbuildLoader(id),
jsx: 'preserve', jsx: 'preserve',
sourcefile: id,
sourcemap: 'inline', sourcemap: 'inline',
}); });
return transformJSX({ return transformJSX({
@ -214,10 +209,9 @@ https://docs.astro.build/en/core-concepts/framework-components/#installing-integ
} }
// downlevel any non-standard syntax, but preserve JSX // downlevel any non-standard syntax, but preserve JSX
const { code: jsxCode } = await esbuild.transform(code, { const { code: jsxCode } = await transformWithEsbuild(code, id, {
loader: getEsbuildLoader(path.extname(id)) as esbuild.Loader, loader: getEsbuildLoader(id),
jsx: 'preserve', jsx: 'preserve',
sourcefile: id,
sourcemap: 'inline', sourcemap: 'inline',
}); });
return await transformJSX({ return await transformJSX({

View file

@ -1,9 +1,8 @@
import { renderMarkdown } from '@astrojs/markdown-remark'; import { renderMarkdown } from '@astrojs/markdown-remark';
import esbuild from 'esbuild';
import fs from 'fs'; import fs from 'fs';
import matter from 'gray-matter'; import matter from 'gray-matter';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import type { Plugin, ResolvedConfig } from 'vite'; import { Plugin, ResolvedConfig, transformWithEsbuild } from 'vite';
import type { AstroSettings } from '../@types/astro'; import type { AstroSettings } from '../@types/astro';
import { pagesVirtualModuleId } from '../core/app/index.js'; import { pagesVirtualModuleId } from '../core/app/index.js';
import { cachedCompilation, CompileProps } from '../core/compile/index.js'; import { cachedCompilation, CompileProps } from '../core/compile/index.js';
@ -224,10 +223,9 @@ export function compiledContent() {
${tsResult}`; ${tsResult}`;
// Compile from `.ts` to `.js` // Compile from `.ts` to `.js`
const { code } = await esbuild.transform(tsResult, { const { code } = await transformWithEsbuild(tsResult, id, {
loader: 'ts', loader: 'ts',
sourcemap: false, sourcemap: false,
sourcefile: id,
}); });
const astroMetadata: AstroPluginMetadata['astro'] = { const astroMetadata: AstroPluginMetadata['astro'] = {

View file

@ -423,7 +423,6 @@ importers:
diff: ^5.1.0 diff: ^5.1.0
eol: ^0.9.1 eol: ^0.9.1
es-module-lexer: ^0.10.5 es-module-lexer: ^0.10.5
esbuild: ^0.14.43
execa: ^6.1.0 execa: ^6.1.0
fast-glob: ^3.2.11 fast-glob: ^3.2.11
github-slugger: ^1.4.0 github-slugger: ^1.4.0
@ -467,7 +466,7 @@ importers:
unified: ^10.1.2 unified: ^10.1.2
unist-util-visit: ^4.1.0 unist-util-visit: ^4.1.0
vfile: ^5.3.2 vfile: ^5.3.2
vite: ~3.2.4 vite: ~3.2.5
vitefu: ^0.2.1 vitefu: ^0.2.1
yargs-parser: ^21.0.1 yargs-parser: ^21.0.1
zod: ^3.17.3 zod: ^3.17.3
@ -496,7 +495,6 @@ importers:
deepmerge-ts: 4.2.2 deepmerge-ts: 4.2.2
diff: 5.1.0 diff: 5.1.0
es-module-lexer: 0.10.5 es-module-lexer: 0.10.5
esbuild: 0.14.54
execa: 6.1.0 execa: 6.1.0
fast-glob: 3.2.12 fast-glob: 3.2.12
github-slugger: 1.5.0 github-slugger: 1.5.0
@ -529,8 +527,8 @@ importers:
typescript: 4.8.4 typescript: 4.8.4
unist-util-visit: 4.1.1 unist-util-visit: 4.1.1
vfile: 5.3.5 vfile: 5.3.5
vite: 3.2.4_sass@1.56.1 vite: 3.2.5_sass@1.56.1
vitefu: 0.2.1_vite@3.2.4 vitefu: 0.2.1_vite@3.2.5
yargs-parser: 21.1.1 yargs-parser: 21.1.1
zod: 3.19.1 zod: 3.19.1
devDependencies: devDependencies:
@ -18150,8 +18148,8 @@ packages:
fsevents: 2.3.2 fsevents: 2.3.2
dev: true dev: true
/vite/3.2.3_@types+node@18.11.9: /vite/3.2.5_@types+node@18.11.9:
resolution: {integrity: sha512-h8jl1TZ76eGs3o2dIBSsvXDLb1m/Ec1iej8ZMdz+PsaFUsftZeWe2CZOI3qogEsMNaywc17gu0q6cQDzh/weCQ==} resolution: {integrity: sha512-4mVEpXpSOgrssFZAOmGIr85wPHKvaDAcXqxVxVRZhljkJOMZi1ibLibzjLHzJvcok8BMguLc7g1W6W/GqZbLdQ==}
engines: {node: ^14.18.0 || >=16.0.0} engines: {node: ^14.18.0 || >=16.0.0}
hasBin: true hasBin: true
peerDependencies: peerDependencies:
@ -18184,8 +18182,8 @@ packages:
fsevents: 2.3.2 fsevents: 2.3.2
dev: false dev: false
/vite/3.2.4_sass@1.56.1: /vite/3.2.5_sass@1.56.1:
resolution: {integrity: sha512-Z2X6SRAffOUYTa+sLy3NQ7nlHFU100xwanq1WDwqaiFiCe+25zdxP1TfCS5ojPV2oDDcXudHIoPnI1Z/66B7Yw==} resolution: {integrity: sha512-4mVEpXpSOgrssFZAOmGIr85wPHKvaDAcXqxVxVRZhljkJOMZi1ibLibzjLHzJvcok8BMguLc7g1W6W/GqZbLdQ==}
engines: {node: ^14.18.0 || >=16.0.0} engines: {node: ^14.18.0 || >=16.0.0}
hasBin: true hasBin: true
peerDependencies: peerDependencies:
@ -18238,7 +18236,7 @@ packages:
vite: 3.2.3 vite: 3.2.3
dev: false dev: false
/vitefu/0.2.1_vite@3.2.4: /vitefu/0.2.1_vite@3.2.5:
resolution: {integrity: sha512-clkvXTAeUf+XQKm3bhWUhT4pye+3acm6YCTGaWhxxIvZZ/QjnA3JA8Zud+z/mO5y5XYvJJhevs5Sjkv/FI8nRw==} resolution: {integrity: sha512-clkvXTAeUf+XQKm3bhWUhT4pye+3acm6YCTGaWhxxIvZZ/QjnA3JA8Zud+z/mO5y5XYvJJhevs5Sjkv/FI8nRw==}
peerDependencies: peerDependencies:
vite: ^3.0.0 vite: ^3.0.0
@ -18246,7 +18244,7 @@ packages:
vite: vite:
optional: true optional: true
dependencies: dependencies:
vite: 3.2.4_sass@1.56.1 vite: 3.2.5_sass@1.56.1
dev: false dev: false
/vitest/0.20.3: /vitest/0.20.3:
@ -18282,7 +18280,7 @@ packages:
local-pkg: 0.4.2 local-pkg: 0.4.2
tinypool: 0.2.4 tinypool: 0.2.4
tinyspy: 1.0.2 tinyspy: 1.0.2
vite: 3.2.3_@types+node@18.11.9 vite: 3.2.5_@types+node@18.11.9
transitivePeerDependencies: transitivePeerDependencies:
- less - less
- sass - sass