-
Notifications
You must be signed in to change notification settings - Fork 287
/
Copy pathmodule.ts
182 lines (156 loc) · 5.39 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
174
175
176
177
178
179
180
181
182
import process from 'node:process'
import { parseURL, withLeadingSlash } from 'ufo'
import { defineNuxtModule, addTemplate, addImports, createResolver, addComponent, addPlugin } from '@nuxt/kit'
import { resolve } from 'pathe'
import { resolveProviders, detectProvider, resolveProvider } from './provider'
import type { ImageProviders, ImageOptions, InputProvider, CreateImageOptions } from './types'
export interface ModuleOptions extends ImageProviders {
inject: boolean
provider: CreateImageOptions['provider']
presets: { [name: string]: ImageOptions }
dir: string
domains: string[]
alias: Record<string, string>
screens: CreateImageOptions['screens']
providers: { [name: string]: InputProvider | any }
densities: number[]
format: CreateImageOptions['format']
quality?: CreateImageOptions['quality']
[key: string]: any
}
export * from './types'
export default defineNuxtModule<ModuleOptions>({
defaults: nuxt => ({
inject: false,
provider: 'auto',
dir: nuxt.options.dir.public,
presets: {},
domains: [] as string[],
sharp: {},
format: ['webp'],
// https://tailwindcss.com/docs/breakpoints
screens: {
'xs': 320,
'sm': 640,
'md': 768,
'lg': 1024,
'xl': 1280,
'xxl': 1536,
'2xl': 1536,
},
providers: {},
alias: {},
densities: [1, 2],
}),
meta: {
name: '@nuxt/image',
configKey: 'image',
compatibility: {
nuxt: '>=3.1.0',
},
},
async setup(options, nuxt) {
const resolver = createResolver(import.meta.url)
// fully resolve directory
options.dir = resolve(nuxt.options.srcDir, options.dir)
// Domains from environment variable
const domainsFromENV = process.env.NUXT_IMAGE_DOMAINS?.replace(/\s/g, '').split(',') || []
// Normalize domains to hostname
options.domains = [...new Set([...options.domains, ...domainsFromENV])]
.map(d => d && (parseURL(d.startsWith('http') ? d : ('http://' + d)).host))
.filter(Boolean) as string[]
// Normalize alias to start with leading slash
options.alias = Object.fromEntries(Object.entries(options.alias).map(e => [withLeadingSlash(e[0]), e[1]]))
options.provider = detectProvider(options.provider)!
if (options.provider) {
options[options.provider] = options[options.provider] || {}
}
options.densities = options.densities || []
const imageOptions: Omit<CreateImageOptions, 'providers' | 'nuxt' | 'runtimeConfig'> = pick(options, [
'screens',
'presets',
'provider',
'domains',
'alias',
'densities',
'format',
'quality',
])
const providers = await resolveProviders(nuxt, options)
// Run setup
for (const p of providers) {
if (typeof p.setup === 'function' && p.name !== 'ipx' && p.name !== 'ipxStatic') {
await p.setup(p, options, nuxt)
}
}
// Transpile and alias runtime
const runtimeDir = resolver.resolve('./runtime')
nuxt.options.alias['#image'] = runtimeDir
nuxt.options.build.transpile.push(runtimeDir)
addImports({
name: 'useImage',
from: resolver.resolve('runtime/composables'),
})
// Add components
addComponent({
name: 'NuxtImg',
filePath: resolver.resolve('./runtime/components/NuxtImg.vue'),
})
addComponent({
name: 'NuxtPicture',
filePath: resolver.resolve('./runtime/components/NuxtPicture.vue'),
})
// Add runtime options
addTemplate({
filename: 'image-options.mjs',
getContents() {
return `
${providers.map(p => `import * as ${p.importName} from '${p.runtime}'`).join('\n')}
export const imageOptions = ${JSON.stringify(imageOptions, null, 2)}
imageOptions.providers = {
${providers.map(p => ` ['${p.name}']: { provider: ${p.importName}, defaults: ${JSON.stringify(p.runtimeOptions)} }`).join(',\n')}
}
`
},
})
nuxt.hook('nitro:init', async (nitro) => {
if (!options.provider || options.provider === 'ipx' || options.provider === 'ipxStatic' || options.ipx) {
const resolvedProvider = nitro.options.static || options.provider === 'ipxStatic'
? 'ipxStatic'
: nitro.options.node ? 'ipx' : 'none'
if (!options.provider || options.provider === 'ipx' || options.provider === 'ipxStatic') {
imageOptions.provider = options.provider = resolvedProvider
}
// initialise provider options
if (resolvedProvider === 'ipxStatic') {
// handle the case of `ipx: {}` existing in options, but deploying a static site
options.ipxStatic ||= options.ipx || {}
}
else {
options[resolvedProvider] = options[resolvedProvider] || {}
}
const p = await resolveProvider(nuxt, resolvedProvider, {
options: options[resolvedProvider],
})
if (!providers.some(p => p.name === resolvedProvider)) {
providers.push(p)
}
if (typeof p.setup === 'function') {
await p.setup(p, options, nuxt)
}
}
})
if (options.inject) {
// Add runtime plugin
addPlugin({ src: resolver.resolve('./runtime/plugin') })
}
// TODO: Transform asset urls that pass to `src` attribute on image components
},
})
function pick<O extends Record<any, any>, K extends keyof O>(obj: O, keys: K[]): Pick<O, K> {
const newobj = {} as Pick<O, K>
for (const key of keys) {
newobj[key] = obj[key]
}
return newobj
}