Support tsconfig aliases in styles (#6566)

This commit is contained in:
Bjorn Lu 2023-03-17 01:04:26 +08:00 committed by GitHub
parent 6c465e958e
commit ea9b3dd72b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 80 additions and 79 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Support tsconfig aliases in styles

View file

@ -1,47 +1,20 @@
import * as path from 'path'; import fs from 'fs';
import path from 'path';
import type { AstroSettings } from '../@types/astro'; import type { AstroSettings } from '../@types/astro';
import type * as vite from 'vite'; import type { Alias, Plugin as VitePlugin } from 'vite';
import type { TsConfigJson } from 'tsconfig-resolver';
/** Result of successfully parsed tsconfig.json or jsconfig.json. */ import slash from 'slash';
export declare interface Alias {
find: RegExp;
replacement: string;
}
/** Returns a path with its slashes replaced with posix slashes. */
const normalize = (pathname: string) => String(pathname).split(path.sep).join(path.posix.sep);
/** Returns a list of compiled aliases. */ /** Returns a list of compiled aliases. */
const getConfigAlias = (settings: AstroSettings): Alias[] | null => { const getConfigAlias = (
/** Closest tsconfig.json or jsconfig.json */ paths: NonNullable<TsConfigJson.CompilerOptions['paths']>,
const config = settings.tsConfig; baseUrl: NonNullable<TsConfigJson.CompilerOptions['baseUrl']>
const configPath = settings.tsConfigPath; ): Alias[] => {
// if no config was found, return null
if (!config || !configPath) return null;
/** Compiler options from tsconfig.json or jsconfig.json. */
const compilerOptions = Object(config.compilerOptions);
// if no compilerOptions.baseUrl was defined, return null
if (!compilerOptions.baseUrl) return null;
// resolve the base url from the configuration file directory
const baseUrl = path.posix.resolve(
path.posix.dirname(normalize(configPath).replace(/^\/?/, '/')),
normalize(compilerOptions.baseUrl)
);
/** List of compiled alias expressions. */
const aliases: Alias[] = []; const aliases: Alias[] = [];
// compile any alias expressions and push them to the list // compile any alias expressions and push them to the list
for (let [alias, values] of Object.entries( for (const [alias, values] of Object.entries(paths)) {
Object(compilerOptions.paths) as { [key: string]: string[] }
)) {
values = [].concat(values as never);
/** Regular Expression used to match a given path. */ /** Regular Expression used to match a given path. */
const find = new RegExp( const find = new RegExp(
`^${[...alias] `^${[...alias]
@ -54,7 +27,7 @@ const getConfigAlias = (settings: AstroSettings): Alias[] | null => {
/** Internal index used to calculate the matching id in a replacement. */ /** Internal index used to calculate the matching id in a replacement. */
let matchId = 0; let matchId = 0;
for (let value of values) { for (const value of values) {
/** String used to replace a matched path. */ /** String used to replace a matched path. */
const replacement = [...path.posix.resolve(baseUrl, value)] const replacement = [...path.posix.resolve(baseUrl, value)]
.map((segment) => (segment === '*' ? `$${++matchId}` : segment === '$' ? '$$' : segment)) .map((segment) => (segment === '*' ? `$${++matchId}` : segment === '$' ? '$$' : segment))
@ -64,14 +37,6 @@ const getConfigAlias = (settings: AstroSettings): Alias[] | null => {
} }
} }
// compile the baseUrl expression and push it to the list
// - `baseUrl` changes the way non-relative specifiers are resolved
// - if `baseUrl` exists then all non-relative specifiers are resolved relative to it
aliases.push({
find: /^(?!\.*\/)(.+)$/,
replacement: `${[...baseUrl].map((segment) => (segment === '$' ? '$$' : segment)).join('')}/$1`,
});
return aliases; return aliases;
}; };
@ -80,39 +45,42 @@ export default function configAliasVitePlugin({
settings, settings,
}: { }: {
settings: AstroSettings; settings: AstroSettings;
}): vite.PluginOption { }): VitePlugin | null {
const { config } = settings; const { tsConfig, tsConfigPath } = settings;
/** Aliases from the tsconfig.json or jsconfig.json configuration. */ if (!tsConfig || !tsConfigPath || !tsConfig.compilerOptions) return null;
const configAlias = getConfigAlias(settings);
// if no config alias was found, bypass this plugin const { baseUrl, paths } = tsConfig.compilerOptions;
if (!configAlias) return {} as vite.PluginOption; if (!baseUrl || !paths) return null;
// resolve the base url from the configuration file directory
const resolvedBaseUrl = path.posix.resolve(
path.posix.dirname(slash(tsConfigPath).replace(/^\/?/, '/')),
slash(baseUrl)
);
const configAlias = getConfigAlias(paths, resolvedBaseUrl);
return { return {
name: 'astro:tsconfig-alias', name: 'astro:tsconfig-alias',
enforce: 'pre', enforce: 'pre',
async resolveId(sourceId: string, importer, options) { config() {
/** Resolved ID conditionally handled by any other resolver. (this gives priority to all other resolvers) */ if (configAlias.length) {
const resolvedId = await this.resolve(sourceId, importer, { skipSelf: true, ...options }); return {
resolve: {
alias: configAlias,
},
};
}
},
resolveId(id) {
if (id.startsWith('.') || id.startsWith('/')) return;
// if any other resolver handles the file, return that resolution // Handle baseUrl mapping for non-relative and non-root imports.
if (resolvedId) return resolvedId; // Since TypeScript only applies `baseUrl` autocompletions for files that exist
// in the filesystem only, we can use this heuristic to skip resolve if needed.
// conditionally resolve the source ID from any matching alias or baseUrl const resolved = path.posix.join(resolvedBaseUrl, id);
for (const alias of configAlias) { if (fs.existsSync(resolved)) {
if (alias.find.test(sourceId)) { return resolved;
/** Processed Source ID with our alias applied. */
const aliasedSourceId = sourceId.replace(alias.find, alias.replacement);
/** Resolved ID conditionally handled by any other resolver. (this also gives priority to all other resolvers) */
const resolvedAliasedId = await this.resolve(aliasedSourceId, importer, {
skipSelf: true,
...options,
});
// if the existing resolvers find the file, return that resolution
if (resolvedAliasedId) return resolvedAliasedId;
}
} }
}, },
}; };

View file

@ -34,5 +34,20 @@ describe('Aliases with tsconfig.json', () => {
const scripts = $('script').toArray(); const scripts = $('script').toArray();
expect(scripts.length).to.be.greaterThan(0); expect(scripts.length).to.be.greaterThan(0);
}); });
it('can load via baseUrl', async () => {
const html = await fixture.fetch('/').then((res) => res.text());
const $ = cheerio.load(html);
expect($('#foo').text()).to.equal('foo');
});
it('works in css @import', async () => {
const html = await fixture.fetch('/').then((res) => res.text());
console.log(html)
// imported css should be bundled
expect(html).to.include('#style-red');
expect(html).to.include('#style-blue');
});
}); });
}); });

View file

@ -0,0 +1 @@
<p id="foo">foo</p>

View file

@ -0,0 +1,2 @@
<p id="style-blue">i am blue</p>
<p id="style-red">i am red</p>

View file

@ -1,5 +1,8 @@
--- ---
import Client from '@components/Client.svelte' import Client from '@components/Client.svelte'
import Foo from 'src/components/Foo.astro';
import StyleComp from 'src/components/Style.astro';
import '@styles/main.css'
--- ---
<html lang="en"> <html lang="en">
<head> <head>
@ -10,6 +13,8 @@ import Client from '@components/Client.svelte'
<body> <body>
<main> <main>
<Client client:load /> <Client client:load />
<Foo />
<StyleComp />
</main> </main>
</body> </body>
</html> </html>

View file

@ -0,0 +1,3 @@
#style-red {
color: red;
}

View file

@ -0,0 +1,5 @@
@import "@styles/extra.css";
#style-blue {
color: blue;
}

View file

@ -5,12 +5,9 @@
"@components/*": [ "@components/*": [
"src/components/*" "src/components/*"
], ],
"@layouts/*": [ "@styles/*": [
"src/layouts/*" "src/styles/*"
], ]
"@assets/*": [
"src/assets/*"
],
} }
} }
} }