2024-07-02 18:28:48 +00:00
|
|
|
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
|
|
import { requireModule, tryResolveModule } from '@nuxt/kit'
|
|
|
|
import type { Nuxt, NuxtOptions } from '@nuxt/schema'
|
2023-03-29 10:59:57 +00:00
|
|
|
import type { InlineConfig as ViteConfig } from 'vite'
|
2024-07-02 18:28:48 +00:00
|
|
|
import { interopDefault } from 'mlly'
|
|
|
|
import type { Plugin } from 'postcss'
|
2021-10-13 20:08:26 +00:00
|
|
|
|
2024-07-02 18:28:48 +00:00
|
|
|
function sortPlugins ({ plugins, order }: NuxtOptions['postcss']): string[] {
|
|
|
|
const names = Object.keys(plugins)
|
|
|
|
return typeof order === 'function' ? order(names) : (order || names)
|
|
|
|
}
|
2024-06-13 22:35:00 +00:00
|
|
|
|
2024-07-02 18:28:48 +00:00
|
|
|
export async function resolveCSSOptions (nuxt: Nuxt): Promise<ViteConfig['css']> {
|
2023-03-29 10:59:57 +00:00
|
|
|
const css: ViteConfig['css'] & { postcss: NonNullable<Exclude<NonNullable<ViteConfig['css']>['postcss'], string>> } = {
|
2021-10-13 20:08:26 +00:00
|
|
|
postcss: {
|
2024-04-05 18:08:32 +00:00
|
|
|
plugins: [],
|
|
|
|
},
|
2021-10-13 20:08:26 +00:00
|
|
|
}
|
|
|
|
|
2024-06-13 22:35:00 +00:00
|
|
|
css.postcss.plugins = []
|
|
|
|
|
2024-07-02 18:28:48 +00:00
|
|
|
const postcssOptions = nuxt.options.postcss
|
|
|
|
|
|
|
|
const cwd = fileURLToPath(new URL('.', import.meta.url))
|
|
|
|
for (const pluginName of sortPlugins(postcssOptions)) {
|
|
|
|
const pluginOptions = postcssOptions.plugins[pluginName]
|
|
|
|
if (!pluginOptions) { continue }
|
|
|
|
|
|
|
|
const path = await tryResolveModule(pluginName, nuxt.options.modulesDir)
|
|
|
|
|
|
|
|
let pluginFn: (opts: Record<string, any>) => Plugin
|
|
|
|
// TODO: use jiti v2
|
|
|
|
if (path) {
|
|
|
|
pluginFn = await import(pathToFileURL(path).href).then(interopDefault)
|
|
|
|
} else {
|
|
|
|
console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\` with ESM. Please report this as a bug.`)
|
|
|
|
// fall back to cjs
|
|
|
|
pluginFn = requireModule(pluginName, { paths: [cwd] })
|
|
|
|
}
|
|
|
|
if (typeof pluginFn === 'function') {
|
|
|
|
css.postcss.plugins.push(pluginFn(pluginOptions))
|
2024-06-13 22:35:00 +00:00
|
|
|
}
|
|
|
|
}
|
2021-10-13 20:08:26 +00:00
|
|
|
|
|
|
|
return css
|
|
|
|
}
|