Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: extends support #499

Merged
merged 16 commits into from
Jul 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
externals: [
'pathe',
'minimatch'
]
})
3 changes: 1 addition & 2 deletions docs/content/2.tailwind/1.config.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ You can learn more about the [Tailwind configuration](https://tailwindcss.com/do
## Overwriting the configuration

You can extend the default configuration:

- with a [tailwind.config.js](#tailwindconfigjs) file
- using the [config option](#config-option)
- with the `tailwindcss:config` Nuxt hook
Expand Down Expand Up @@ -89,7 +90,6 @@ This config has less priority over the [tailwind.config.js](#tailwindconfigjs) f

::


### `tailwindcss:config` hook

::alert{type="warning"}
Expand Down Expand Up @@ -188,7 +188,6 @@ module.exports = {
}
```


## Referencing in the application

It can often be useful to reference Tailwind configuration values at runtime, e.g. to access some of your theme values when dynamically applying inline styles in a component.
Expand Down
16 changes: 16 additions & 0 deletions docs/content/3.examples/6.content.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
title: '@nuxt/content'
description: 'Discover how powerful it is to use TailwindCSS in @nuxt/content Markdown files!'
---

The module supports [@nuxt/content](https://content.nuxtjs.org), meaning you can use Tailwind classes inside your content files with MDC syntax!

```md
Hello, this is a [Markdown]{.px-1 .bg-blue-200 .rounded-lg} file!

::div{.w-full .bg-green-200 .p-4}
Another way to use it!
::
```

Learn more about the [Span Syntax](https://content.nuxtjs.org/guide/writing/mdc#span-text) and how to use classes in Markdown files!
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"codecov": "latest",
"eslint": "latest",
"nuxt": "npm:nuxt3@latest",
"@nuxt/content": "npm:@nuxt/content-edge@latest",
"standard-version": "latest"
}
}
13 changes: 13 additions & 0 deletions playground/content/content.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
::div{.my-4}
[@nuxt/content support]{.px-4 .text-xl .font-bold}
::

---

::div{.my-4 .px-4}
Hello World! :wave:

This is an integration test with [@nuxt/content](https://content.nuxtjs.org){.font-bold .hover:text-blue-500}! :smile:

It feels pretty smooth!
::
12 changes: 9 additions & 3 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { defineNuxtConfig } from 'nuxt'
import tailwindModule from '..'
import tailwindModule from '../src/module'

export default defineNuxtConfig({
buildModules: [
extends: ['./theme'],
modules: [
'@nuxt/content',
tailwindModule
],
tailwindcss: {
exposeConfig: true
exposeConfig: true,
configPath: './tailwind.config.js'
},
content: {
documentDriven: true
},
css: [
// Including Inter CSS is the first component to reproduce HMR issue. It also causes playground to look better,
Expand Down
7 changes: 6 additions & 1 deletion playground/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
<div class="max-w-screen-lg p-4 mx-auto space-y-4">
<div>
<span class="pr-1 font-medium">This is a HMR test, try changing the color:</span>
<span class="text-indigo-500">meow!</span>
<span class="text-brand">meow!</span>
</div>
<div>
<NuxtLink to="/content" class="underline hover:text-indigo-500">
Visit the /content page to check out the @nuxt/content integration!
</NuxtLink>
</div>
<div>
<span class="text-sm font-semibold text-gray-700">Resolved tailwind config:</span>
Expand Down
15 changes: 15 additions & 0 deletions playground/theme/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { fileURLToPath } from 'url'
import { defineNuxtConfig } from 'nuxt'
import { resolve } from 'pathe'
import tailwindModule from '../../src/module'

const themeDir = fileURLToPath(new URL('./', import.meta.url))
const resolveThemeDir = (path: string) => resolve(themeDir, path)

export default defineNuxtConfig({
modules: [tailwindModule],

tailwindcss: {
configPath: resolveThemeDir('./tailwind.config.js')
}
})
9 changes: 9 additions & 0 deletions playground/theme/tailwind.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default {
theme: {
extend: {
colors: {
brand: '#0070f3'
}
}
}
}
4 changes: 2 additions & 2 deletions src/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { isAbsolute, resolve } from 'path'
import { HmrContext, Plugin } from 'vite'
import minimatch from 'minimatch'

export default function (tailwindConfig, rootDir: string, cssPath: string): Plugin {
const resolvedContent: string[] = tailwindConfig.content.map(f => !isAbsolute(f) ? resolve(rootDir, f) : f)
export default function (tailwindConfig: any = {}, rootDir: string, cssPath: string): Plugin {
const resolvedContent: string[] = (tailwindConfig.content || []).map(f => !isAbsolute(f) ? resolve(rootDir, f) : f)

return {
name: 'nuxt:tailwindcss',
Expand Down
139 changes: 107 additions & 32 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,37 @@
import { join, relative } from 'path'
import { existsSync } from 'fs'
import { defuArrayFn } from 'defu'
import { join, relative } from 'pathe'
import defu, { defuArrayFn } from 'defu'
import chalk from 'chalk'
import consola from 'consola'
import {
defineNuxtModule,
installModule,
addTemplate,
addDevServerHandler,
requireModule,
isNuxt2,
createResolver,
resolvePath,
addVitePlugin
addVitePlugin,
tryRequireModule
} from '@nuxt/kit'
import { name, version } from '../package.json'
import vitePlugin from './hmr'
import defaultTailwindConfig from './tailwind.config'

const logger = consola.withScope('nuxt:tailwindcss')

const layerPaths = (srcDir: string) => ([
`${srcDir}/components/**/*.{vue,js,ts}`,
`${srcDir}/layouts/**/*.vue`,
`${srcDir}/pages/**/*.vue`,
`${srcDir}/composables/**/*.{js,ts}`,
`${srcDir}/plugins/**/*.{js,ts}`,
`${srcDir}/App.{js,ts,vue}`,
`${srcDir}/app.{js,ts,vue}`,
`${srcDir}/Error.{js,ts,vue}`,
`${srcDir}/error.{js,ts,vue}`
])

export interface ModuleHooks {
'tailwindcss:config': (tailwindConfig: any) => void
}
Expand All @@ -33,46 +45,76 @@ export default defineNuxtModule({
defaults: nuxt => ({
configPath: 'tailwind.config',
cssPath: join(nuxt.options.dir.assets, 'css/tailwind.css'),
config: defaultTailwindConfig(nuxt.options),
config: defaultTailwindConfig(),
viewer: true,
exposeConfig: false,
injectPosition: 0,
disableHmrHotfix: false
}),
async setup (moduleOptions, nuxt) {
const configPath = await resolvePath(moduleOptions.configPath)
const cssPath = await resolvePath(moduleOptions.cssPath, { extensions: ['.css', '.sass', '.scss', '.less', '.styl'] })
const injectPosition = ~~Math.min(moduleOptions.injectPosition, (nuxt.options.css || []).length + 1)
/**
* Config file handling
*/

// Include CSS file in project css
let resolvedCss: string
if (typeof cssPath === 'string') {
if (existsSync(cssPath)) {
logger.info(`Using Tailwind CSS from ~/${relative(nuxt.options.srcDir, cssPath)}`)
resolvedCss = cssPath
} else {
logger.info('Using default Tailwind CSS file from runtime/tailwind.css')
resolvedCss = createResolver(import.meta.url).resolve('runtime/tailwind.css')
const configPaths = []
const contentPaths = []

/**
* Push config paths into `configPaths` without extension.
* Allows next steps of processing to try both .js / .ts when resolving the config.
*/
const addConfigPath = async (path: string | string[]) => {
if (typeof path === 'string') {
path = (await resolvePath(path)).split('.').slice(0, -1).join('.')
configPaths.push(path)
return
}

if (Array.isArray(path)) {
for (let _path of path) {
_path = (await resolvePath(_path)).split('.').slice(0, -1).join('.')
configPaths.push()
}
}
}

// Inject only if this file isn't listed already by user (e.g. user may put custom path both here and in css):
const resolvedNuxtCss = await Promise.all(nuxt.options.css.map(p => resolvePath(p)))
if (!resolvedNuxtCss.includes(resolvedCss)) {
nuxt.options.css.splice(injectPosition, 0, resolvedCss)
// Support `extends` directories
if (nuxt.options._layers && nuxt.options._layers.length > 1) {
interface NuxtLayer {
config: any
configFile: string
cwd: string
}

for (const layer of (nuxt.options._layers as NuxtLayer[])) {
await addConfigPath(layer?.config?.tailwindcss?.configPath || join(layer.cwd, 'tailwind.config'))
contentPaths.push(...layerPaths(layer.cwd))
}
} else {
await addConfigPath(moduleOptions.configPath)
contentPaths.push(...layerPaths(nuxt.options.srcDir))
}

// Extend the Tailwind config
// Watch the Tailwind config file to restart the server
if (nuxt.options.dev) {
configPaths.forEach(path => nuxt.options.watch.push(path))
}

// Recursively resolve each config and merge tailwind configs together.
let tailwindConfig: any = {}
if (existsSync(configPath)) {
tailwindConfig = requireModule(configPath, { clearCache: true })
logger.info(`Merging Tailwind config from ~/${relative(nuxt.options.srcDir, configPath)}`)
for (const configPath of configPaths) {
const _tailwindConfig = tryRequireModule(configPath, { clearCache: true })

// Transform purge option from Array to object with { content }
if (Array.isArray(tailwindConfig.purge)) {
tailwindConfig.content = tailwindConfig.purge
if (_tailwindConfig && Array.isArray(_tailwindConfig.purge)) {
_tailwindConfig.content = _tailwindConfig.purge
}

tailwindConfig = defu(_tailwindConfig || {}, tailwindConfig)
}

tailwindConfig.content = [...(tailwindConfig.content || []), ...contentPaths]

// Merge with our default purgecss default
tailwindConfig = defuArrayFn(tailwindConfig, moduleOptions.config)

Expand All @@ -93,18 +135,43 @@ export default defineNuxtModule({
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())

/**
* CSS file handling
*/

const cssPath = await resolvePath(moduleOptions.cssPath, { extensions: ['.css', '.sass', '.scss', '.less', '.styl'] })
const injectPosition = ~~Math.min(moduleOptions.injectPosition, (nuxt.options.css || []).length + 1)

// Include CSS file in project css
let resolvedCss: string
if (typeof cssPath === 'string') {
if (existsSync(cssPath)) {
logger.info(`Using Tailwind CSS from ~/${relative(nuxt.options.srcDir, cssPath)}`)
resolvedCss = cssPath
} else {
logger.info('Using default Tailwind CSS file from runtime/tailwind.css')
// @ts-ignore
resolvedCss = createResolver(import.meta.url).resolve('runtime/tailwind.css')
}
}

// Inject only if this file isn't listed already by user (e.g. user may put custom path both here and in css):
const resolvedNuxtCss = await Promise.all(nuxt.options.css.map(p => resolvePath(p)))
if (!resolvedNuxtCss.includes(resolvedCss)) {
nuxt.options.css.splice(injectPosition, 0, resolvedCss)
}

/**
* PostCSS 8 support for Nuxt 2
*/

// Setup postcss plugins
// https://tailwindcss.com/docs/using-with-preprocessors#future-css-features
const postcssOptions =
Expand All @@ -120,11 +187,19 @@ export default defineNuxtModule({
await installModule('@nuxt/postcss8')
}

/**
* Vite HMR support
*/

if (nuxt.options.dev && !moduleOptions.disableHmrHotfix) {
// Insert Vite plugin to work around HMR issue
addVitePlugin(vitePlugin(tailwindConfig, nuxt.options.rootDir, resolvedCss))
}

/**
* Viewer
*/

// Add _tailwind config viewer endpoint
if (nuxt.options.dev && moduleOptions.viewer) {
const route = '/_tailwind'
Expand Down
11 changes: 1 addition & 10 deletions src/tailwind.config.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
// Learn more at https://tailwindcss.com/docs/configuration
import { Config } from 'tailwindcss'

export default ({ srcDir }): Config => ({
export default (): Config => ({
theme: {
extend: {}
},
plugins: [],
content: [
`${srcDir}/components/**/*.{vue,js,ts}`,
`${srcDir}/layouts/**/*.vue`,
`${srcDir}/pages/**/*.vue`,
`${srcDir}/composables/**/*.{js,ts}`,
`${srcDir}/plugins/**/*.{js,ts}`,
`${srcDir}/App.{js,ts,vue}`,
`${srcDir}/app.{js,ts,vue}`,
`${srcDir}/Error.{js,ts,vue}`,
`${srcDir}/error.{js,ts,vue}`
// TODO: This makes issues with import protection
// Split in two files to avoid watching issues (https://github.com/nuxt-community/tailwindcss-module/issues/359)
// `${rootDir}/nuxt.config.js`,
Expand Down
Loading