-
Notifications
You must be signed in to change notification settings - Fork 180
/
module.ts
130 lines (117 loc) · 4.62 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
import { join, relative } from 'path'
import { existsSync } from 'fs'
import defu from 'defu'
import chalk from 'chalk'
import { withTrailingSlash } from 'ufo'
import consola from 'consola'
import {
defineNuxtModule,
installModule,
addTemplate,
addServerMiddleware,
resolveAlias,
requireModule,
isNuxt2,
createResolver,
resolvePath
} from '@nuxt/kit'
import { name, version } from '../package.json'
import defaultTailwindConfig from './tailwind.config'
const logger = consola.withScope('nuxt:tailwindcss')
export interface ModuleHooks {
'tailwindcss:config': (tailwindConfig: any) => void
}
export default defineNuxtModule({
meta: {
name,
version,
configKey: 'tailwindcss'
},
defaults: nuxt => ({
configPath: 'tailwind.config.js',
cssPath: join(nuxt.options.dir.assets, 'css/tailwind.css'),
config: defaultTailwindConfig(nuxt.options),
viewer: true,
exposeConfig: false,
injectPosition: 0
}),
async setup (moduleOptions, nuxt) {
const configPath = await resolvePath(moduleOptions.configPath)
const cssPath = moduleOptions.cssPath && resolveAlias(moduleOptions.cssPath)
const injectPosition = ~~Math.min(moduleOptions.injectPosition, (nuxt.options.css || []).length + 1)
// Include CSS file in project css
if (typeof cssPath === 'string') {
if (existsSync(cssPath)) {
logger.info(`Using Tailwind CSS from ~/${relative(nuxt.options.srcDir, cssPath)}`)
nuxt.options.css.splice(injectPosition, 0, cssPath)
} else {
const resolver = createResolver(import.meta.url)
nuxt.options.css.splice(injectPosition, 0, resolver.resolve('runtime/tailwind.css'))
}
}
// Extend the Tailwind config
let tailwindConfig: any = {}
if (existsSync(configPath)) {
tailwindConfig = requireModule(configPath, { clearCache: true })
logger.info(`Merging Tailwind config from ~/${relative(nuxt.options.srcDir, configPath)}`)
// Transform purge option from Array to object with { content }
if (Array.isArray(tailwindConfig.purge)) {
tailwindConfig.content = tailwindConfig.purge
}
}
// Merge with our default purgecss default
tailwindConfig = defu.arrayFn(tailwindConfig, moduleOptions.config)
// Expose resolved tailwind config as an alias
// https://tailwindcss.com/docs/configuration/#referencing-in-javascript
if (moduleOptions.exposeConfig) {
const resolveConfig = await import('tailwindcss/resolveConfig').then(r => r.default || r)
const resolvedConfig = resolveConfig(tailwindConfig)
const template = addTemplate({
filename: 'tailwind.config.mjs',
getContents: () => `export default ${JSON.stringify(resolvedConfig, null, 2)}`
})
nuxt.options.alias['#tailwind-config'] = template.dst
}
// Watch the Tailwind config file to restart the server
if (nuxt.options.dev) {
nuxt.options.watch.push(configPath)
}
// Allow extending tailwindcss config by other modules
// @ts-ignore
await nuxt.callHook('tailwindcss:config', tailwindConfig)
// Compute tailwindConfig hash
tailwindConfig._hash = String(Date.now())
// Setup postcss plugins
// https://tailwindcss.com/docs/using-with-preprocessors#future-css-features
const postcssPlugins = {
'postcss-nesting': {},
'postcss-custom-properties': {},
tailwindcss: tailwindConfig
}
if (isNuxt2()) {
const postcssOptions = nuxt.options.build.postcss as any
postcssOptions.plugins = defu(postcssOptions.plugins, postcssPlugins)
await installModule('@nuxt/postcss8')
} else {
const postcssOptions = nuxt.options.build.postcss.postcssOptions
postcssOptions.plugins = postcssOptions.plugins || {}
postcssOptions.plugins = defu(postcssOptions.plugins, postcssPlugins)
}
// Add _tailwind config viewer endpoint
if (nuxt.options.dev && moduleOptions.viewer) {
const path = '/_tailwind/'
const createServer = await import('tailwind-config-viewer/server/index.js').then(r => r.default || r)
const { withoutTrailingSlash } = await import('ufo')
const _viewerDevMiddleware = createServer({ tailwindConfigProvider: () => tailwindConfig }).asMiddleware()
const viewerDevMiddleware = (req, res) => {
if (req.originalUrl === withoutTrailingSlash(path)) {
res.writeHead(301, { Location: withTrailingSlash(req.originalUrl) })
res.end()
}
_viewerDevMiddleware(req, res)
}
addServerMiddleware({ path, handler: viewerDevMiddleware })
nuxt.hook('listen', () => { logger.info(`Tailwind Viewer: ${chalk.underline.yellow(path)}`) })
}
}
})