1- import { join } from 'node:path'
21import fs from 'node:fs/promises'
32import { existsSync } from 'node:fs'
3+ import { join , isAbsolute } from 'node:path'
44import { hash } from 'ohash'
55import { addPlugin , addServerPlugin , addTemplate , addTypeTemplate , createResolver , defineNuxtModule } from '@nuxt/kit'
66
@@ -44,6 +44,18 @@ export interface ModuleOptions {
4444 * ```
4545 */
4646 transformFile : string
47+
48+ /**
49+ * @default 'nuxt-style-extractor'
50+ * @description If you want to invalidate all caches, then change the baseHash
51+ */
52+ baseHash : string
53+
54+ /**
55+ * @default 'public, max-age=31536000, immutable'
56+ * @description Set cache header, valid only when ssr is in production
57+ */
58+ cacheControl : string | null
4759}
4860
4961export default defineNuxtModule < ModuleOptions > ( {
@@ -55,6 +67,8 @@ export default defineNuxtModule<ModuleOptions>({
5567 minify : true ,
5668 removeUnused : true ,
5769 transformFile : '' ,
70+ baseHash : 'nuxt-style-extractor' ,
71+ cacheControl : 'public, max-age=31536000, immutable' ,
5872 } ,
5973 async setup ( _options , nuxt ) {
6074 const resolver = createResolver ( import . meta. url )
@@ -85,20 +99,20 @@ export default defineNuxtModule<ModuleOptions>({
8599 } )
86100 }
87101
102+ const transformFile = getTransformFile ( )
103+
88104 addTemplate ( {
89105 filename : 'nuxt-style-extractor-config-hash.js' ,
90- getContents ( ) {
91- return `export const configHash = "${ hash ( _options ) } "`
106+ async getContents ( ) {
107+ const modeText = await fs . readFile ( transformFile , 'utf-8' )
108+ return `export const configHash = "${ hash ( [ _options , modeText ] ) } "`
92109 } ,
93110 } )
94111
95112 addTemplate ( {
96113 filename : 'nuxt-style-extractor-transform.js' ,
97114 getContents ( ) {
98- if ( _options . transformFile !== '' ) {
99- return fs . readFile ( _options . transformFile , 'utf-8' )
100- }
101- return fs . readFile ( getDefaultTransformFile ( ) , 'utf-8' )
115+ return fs . readFile ( transformFile , 'utf-8' )
102116 } ,
103117 } )
104118
@@ -109,7 +123,20 @@ export default defineNuxtModule<ModuleOptions>({
109123 } ,
110124 } )
111125
112- function getDefaultTransformFile ( ) {
126+ if ( _options . cacheControl && ! nuxt . options . dev ) {
127+ nuxt . options . routeRules ??= { }
128+ nuxt . options . routeRules [ '/_css/*' ] = {
129+ headers : {
130+ 'Cache-Control' : _options . cacheControl ,
131+ } ,
132+ }
133+ }
134+
135+ function getTransformFile ( ) {
136+ if ( _options . transformFile !== '' ) {
137+ return isAbsolute ( _options . transformFile ) ? _options . transformFile : join ( nuxt . options . rootDir , _options . transformFile )
138+ }
139+
113140 if ( _options . minify && _options . removeUnused ) {
114141 return resolver . resolve ( './runtime/transforms/best.js' )
115142 }
0 commit comments