-
Notifications
You must be signed in to change notification settings - Fork 97
/
module.ts
173 lines (156 loc) 路 5.19 KB
/
module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { promises as fsp } from 'fs'
import { join, resolve } from 'pathe'
import { addPlugin, addTemplate, defineNuxtModule, isNuxt2, addComponent, addImports, createResolver } from '@nuxt/kit'
import { name, version } from '../package.json'
const DEFAULTS: ModuleOptions = {
preference: 'system',
fallback: 'light',
hid: 'nuxt-color-mode-script',
globalName: '__NUXT_COLOR_MODE__',
componentName: 'ColorScheme',
classPrefix: '',
classSuffix: '-mode',
dataValue: '',
storageKey: 'nuxt-color-mode',
disableTransition: false
}
export default defineNuxtModule({
meta: {
name,
version,
configKey: 'colorMode',
compatibility: {
bridge: true
}
},
defaults: DEFAULTS,
async setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
// Read script from disk and add to options
const scriptPath = await resolver.resolve('./script.min.js')
const scriptT = await fsp.readFile(scriptPath, 'utf-8')
type ScriptOption = 'storageKey' | 'preference' | 'globalName' | 'classPrefix' | 'classSuffix' | 'dataValue' | 'classPrefix' | 'classSuffix' | 'dataValue' | 'fallback'
options.script = scriptT.replace(/<%= options\.([^ ]+) %>/g, (_, option: ScriptOption) => options[option])
// Inject options via virtual template
nuxt.options.alias['#color-mode-options'] = addTemplate({
filename: 'color-mode-options.mjs',
getContents: () => Object.entries(options).map(([key, value]) =>
`export const ${key} = ${JSON.stringify(value, null, 2)}
`).join('\n')
}).dst
const runtimeDir = await resolver.resolve('./runtime')
nuxt.options.build.transpile.push(runtimeDir)
// Add plugins
for (const template of ['plugin.client', 'plugin.server']) {
addPlugin(resolve(runtimeDir, template))
}
addComponent({ name: options.componentName, filePath: resolve(runtimeDir, 'component.' + (isNuxt2() ? 'vue2' : 'vue3') + '.vue') })
addImports({ name: 'useColorMode', as: 'useColorMode', from: resolve(runtimeDir, 'composables') })
// Nuxt 3 and Bridge - inject script
nuxt.hook('nitro:config', (config) => {
config.externals = config.externals || {}
config.externals.inline = config.externals.inline || []
config.externals.inline.push(runtimeDir)
config.virtual = config.virtual || {}
config.virtual['#color-mode-options'] = `export const script = ${JSON.stringify(options.script, null, 2)}`
config.plugins = config.plugins || []
config.plugins.push(resolve(runtimeDir, 'nitro-plugin'))
})
if (!isNuxt2()) {
return
}
// Nuxt 2 - SSR false
// @ts-expect-error TODO: add nuxt2 types when merged to bridge
nuxt.hook('vue-renderer:spa:prepareContext', ({ head }) => {
const script = {
hid: options.hid,
innerHTML: options.script,
pbody: true
}
head.script.push(script)
const serializeProp = '__dangerouslyDisableSanitizersByTagID'
head[serializeProp] = head[serializeProp] || {}
head[serializeProp][options.hid] = ['innerHTML']
})
const createHash = await import('crypto').then(r => r.createHash)
// Nuxt 2 - SSR true
// @ts-expect-error TODO: add nuxt2 types when merged to bridge
nuxt.hook('vue-renderer:ssr:csp', (cspScriptSrcHashes) => {
// @ts-expect-error TODO: add nuxt2 types when merged to bridge
const { csp } = nuxt.options.render
const hash = createHash((csp as any).hashAlgorithm)
hash.update(options.script!)
cspScriptSrcHashes.push(
`'${(csp as any).hashAlgorithm}-${hash.digest('base64')}'`
)
})
// In Nuxt 2 dev mode we also inject full script via webpack entrypoint for storybook compatibility
if (nuxt.options.dev) {
const { dst } = addTemplate({
src: scriptPath,
filename: join('color-mode', 'script.min.js'),
options
})
nuxt.hook('webpack:config', (configs) => {
for (const config of configs) {
if (config.name !== 'server') {
(config.entry as any).app.unshift(resolve(nuxt.options.buildDir, dst!))
}
}
})
}
}
})
export interface ModuleOptions {
/**
* The default value of $colorMode.preference
* @default `system`
*/
preference: string
/**
* Fallback value if no system preference found
* @default `light`
*/
fallback: string
/**
* @default `nuxt-color-mode-script`
*/
hid: string
/**
* @default `__NUXT_COLOR_MODE__`
*/
globalName: string
/**
* @default `ColorScheme`
*/
componentName: string
/**
* @default ''
*/
classPrefix: string
/**
* @default '-mode'
*/
classSuffix: string
/**
* Whether to add a data attribute to the html tag. If set, it defines the key of the data attribute.
* For example, setting this to `theme` will output `<html data-theme="dark">` if dark mode is enabled.
* @default ''
*/
dataValue: string
/**
* @default 'nuxt-color-mode'
*/
storageKey: string
/**
* The script that will be injected into the head of the page
*/
script?: string
/**
* Disable transition on switch
*
* @see https://paco.me/writing/disable-theme-transitions
* @default false
*/
disableTransition?: boolean
}