Robin Malfait d68a780f98
Auto source detection improvements (#14820)
This PR introduces a new `source(…)` argument and improves on the
existing `@source`. The goal of this PR is to make the automatic source
detection configurable, let's dig in.

By default, we will perform automatic source detection starting at the
current working directory. Auto source detection will find plain text
files (no binaries, images, ...) and will ignore git-ignored files.

If you want to start from a different directory, you can use the new
`source(…)` next to the `@import "tailwindcss/utilities"
layer(utilities) source(…)`.

E.g.:

```css
/* ./src/styles/index.css */
@import 'tailwindcss/utilities' layer(utilities) source('../../');
```

Most people won't split their source files, and will just use the simple
`@import "tailwindcss";`, because of this reason, you can use
`source(…)` on the import as well:

E.g.:

```css
/* ./src/styles/index.css */
@import 'tailwindcss' source('../../');
```

Sometimes, you want to rely on auto source detection, but also want to
look in another directory for source files. In this case, yuo can use
the `@source` directive:

```css
/* ./src/index.css */
@import 'tailwindcss';

/* Look for `blade.php` files in `../resources/views` */
@source '../resources/views/**/*.blade.php';
```

However, you don't need to specify the extension, instead you can just
point the directory and all the same automatic source detection rules
will apply.

```css
/* ./src/index.css */
@import 'tailwindcss';

@source '../resources/views';
```

If, for whatever reason, you want to disable the default source
detection feature entirely, and only want to rely on very specific glob
patterns you define, then you can disable it via `source(none)`.

```css
/* Completely disable the default auto source detection */
@import 'tailwindcss' source(none);

/* Only look at .blade.php files, nothing else  */
@source "../resources/views/**/*.blade.php";
```

Note: even with `source(none)`, if your `@source` points to a directory,
then auto source detection will still be performed in that directory. If
you don't want that, then you can simply add explicit files in the globs
as seen in the previous example.

```css
/* Completely disable the default auto source detection */
@import 'tailwindcss' source(none);

/* Run auto source detection in `../resources/views` */
@source "../resources/views";
```

---------

Co-authored-by: Jordan Pittman <jordan@cryptica.me>
Co-authored-by: Adam Wathan <4323180+adamwathan@users.noreply.github.com>
2024-10-29 20:33:34 +00:00

173 lines
4.9 KiB
TypeScript

import EnhancedResolve from 'enhanced-resolve'
import { createJiti, type Jiti } from 'jiti'
import fs from 'node:fs'
import fsPromises from 'node:fs/promises'
import path, { dirname } from 'node:path'
import { pathToFileURL } from 'node:url'
import {
__unstable__loadDesignSystem as ___unstable__loadDesignSystem,
compile as _compile,
} from 'tailwindcss'
import { getModuleDependencies } from './get-module-dependencies'
export async function compile(
css: string,
{ base, onDependency }: { base: string; onDependency: (path: string) => void },
) {
let compiler = await _compile(css, {
base,
async loadModule(id, base) {
return loadModule(id, base, onDependency)
},
async loadStylesheet(id, base) {
return loadStylesheet(id, base, onDependency)
},
})
// Verify if the `source(…)` path exists (until the glob pattern starts)
if (compiler.root && compiler.root !== 'none') {
let globSymbols = /[*{]/
let basePath = []
for (let segment of compiler.root.pattern.split('/')) {
if (globSymbols.test(segment)) {
break
}
basePath.push(segment)
}
let exists = await fsPromises
.stat(path.resolve(base, basePath.join('/')))
.then((stat) => stat.isDirectory())
.catch(() => false)
if (!exists) {
throw new Error(`The \`source(${compiler.root.pattern})\` does not exist`)
}
}
return compiler
}
export async function __unstable__loadDesignSystem(css: string, { base }: { base: string }) {
return ___unstable__loadDesignSystem(css, {
base,
async loadModule(id, base) {
return loadModule(id, base, () => {})
},
async loadStylesheet(id, base) {
return loadStylesheet(id, base, () => {})
},
})
}
export async function loadModule(id: string, base: string, onDependency: (path: string) => void) {
if (id[0] !== '.') {
let resolvedPath = await resolveJsId(id, base)
if (!resolvedPath) {
throw new Error(`Could not resolve '${id}' from '${base}'`)
}
let module = await importModule(pathToFileURL(resolvedPath).href)
return {
base: dirname(resolvedPath),
module: module.default ?? module,
}
}
let resolvedPath = await resolveJsId(id, base)
if (!resolvedPath) {
throw new Error(`Could not resolve '${id}' from '${base}'`)
}
let [module, moduleDependencies] = await Promise.all([
importModule(pathToFileURL(resolvedPath).href + '?id=' + Date.now()),
getModuleDependencies(resolvedPath),
])
for (let file of moduleDependencies) {
onDependency(file)
}
return {
base: dirname(resolvedPath),
module: module.default ?? module,
}
}
async function loadStylesheet(id: string, base: string, onDependency: (path: string) => void) {
let resolvedPath = await resolveCssId(id, base)
if (!resolvedPath) throw new Error(`Could not resolve '${id}' from '${base}'`)
onDependency(resolvedPath)
if (typeof globalThis.__tw_readFile === 'function') {
let file = await globalThis.__tw_readFile(resolvedPath, 'utf-8')
if (file) {
return {
base: path.dirname(resolvedPath),
content: file,
}
}
}
let file = await fsPromises.readFile(resolvedPath, 'utf-8')
return {
base: path.dirname(resolvedPath),
content: file,
}
}
// Attempts to import the module using the native `import()` function. If this
// fails, it sets up `jiti` and attempts to import this way so that `.ts` files
// can be resolved properly.
let jiti: null | Jiti = null
async function importModule(path: string): Promise<any> {
try {
return await import(path)
} catch (error) {
jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false })
return await jiti.import(path)
}
}
const cssResolver = EnhancedResolve.ResolverFactory.createResolver({
fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),
useSyncFileSystemCalls: true,
extensions: ['.css'],
mainFields: ['style'],
conditionNames: ['style'],
})
async function resolveCssId(id: string, base: string): Promise<string | false | undefined> {
if (typeof globalThis.__tw_resolve === 'function') {
let resolved = globalThis.__tw_resolve(id, base)
if (resolved) {
return Promise.resolve(resolved)
}
}
return runResolver(cssResolver, id, base)
}
const jsResolver = EnhancedResolve.ResolverFactory.createResolver({
fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),
useSyncFileSystemCalls: true,
extensions: ['.js', '.json', '.node', '.ts'],
conditionNames: import.meta.url ? ['node', 'import'] : ['node', 'require'],
})
function resolveJsId(id: string, base: string): Promise<string | false | undefined> {
return runResolver(jsResolver, id, base)
}
function runResolver(
resolver: EnhancedResolve.Resolver,
id: string,
base: string,
): Promise<string | false | undefined> {
return new Promise((resolve, reject) =>
resolver.resolve({}, base, id, {}, (err, result) => {
if (err) return reject(err)
resolve(result)
}),
)
}