@@ -2,6 +2,7 @@ import type { TailwindV4CssSource } from 'tailwindcss-patch'
22import type webpack from 'webpack'
33import type { AppType } from '@/types'
44import { Buffer } from 'node:buffer'
5+ import path from 'node:path'
56import process from 'node:process'
67import { inspect } from 'node:util'
78import { ensurePosix } from '@weapp-tailwindcss/shared'
@@ -45,6 +46,32 @@ function applyCssImportRewrite(source: string, options: CssImportRewriteLoaderOp
4546 return rewritten ?? source
4647}
4748
49+ function isPackageJsonImportRequest ( request : string ) {
50+ return request . startsWith ( '#' )
51+ }
52+
53+ function toRootRelativeConfigPath ( configPath : string , rootContext : string | undefined ) {
54+ if ( ! rootContext ) {
55+ return ensurePosix ( configPath )
56+ }
57+ const relative = ensurePosix ( path . relative ( rootContext , configPath ) )
58+ return relative . startsWith ( '.' ) ? relative : `./${ relative } `
59+ }
60+
61+ function normalizeCssConfigDirectives ( source : string , resourcePath ?: string , rootContext ?: string ) {
62+ if ( ! resourcePath ) {
63+ return source
64+ }
65+ const base = path . dirname ( resourcePath )
66+ return source . replace ( / @ c o n f i g \s + ( [ " ' ] ) ( .+ ?) \1\s * ; ? / g, ( full , quote : string , request : string ) => {
67+ if ( path . isAbsolute ( request ) || isPackageJsonImportRequest ( request ) ) {
68+ return full
69+ }
70+ const resolved = path . resolve ( base , request )
71+ return `@config ${ quote } ${ toRootRelativeConfigPath ( resolved , rootContext ) } ${ quote } ;`
72+ } )
73+ }
74+
4875export function transformCssImportRewriteSource (
4976 source : string | Buffer ,
5077 options : CssImportRewriteLoaderOptions | undefined ,
@@ -77,10 +104,20 @@ const WeappTwCssImportRewriteLoader: webpack.LoaderDefinitionFunction<CssImportR
77104 const registerTask = typeof input === 'string' && hasTailwindRootDirectives ( input , { importFallback : true } )
78105 ? opt ?. tailwindcssImportRewrite ?. registerCssSource ?.( {
79106 file : this . resourcePath ,
80- css : normalizeTailwindSourceForGenerator ( input , { importFallback : true } ) ,
107+ css : normalizeCssConfigDirectives (
108+ normalizeTailwindSourceForGenerator ( input , { importFallback : true } ) ,
109+ this . resourcePath ,
110+ this . rootContext ,
111+ ) ,
81112 } )
82113 : undefined
83- const transform = ( ) => transformCssImportRewriteSource ( source , opt )
114+ const transform = ( ) => {
115+ const transformed = transformCssImportRewriteSource ( source , opt )
116+ if ( typeof transformed === 'string' ) {
117+ return normalizeCssConfigDirectives ( transformed , this . resourcePath , this . rootContext )
118+ }
119+ return transformed
120+ }
84121 if ( registerTask && typeof ( registerTask as PromiseLike < void > ) . then === 'function' ) {
85122 return Promise . resolve ( registerTask ) . then ( transform )
86123 }
0 commit comments