Skip to content

Commit

Permalink
feat: more adaptive content paths (#744)
Browse files Browse the repository at this point in the history
* chore: initial

* chore: extensions

* chore: update

* chore: update test

* chore: add conditions for composables and utils

* chore: update

* chore: update tests

* chore: finish tests
  • Loading branch information
ineshbose authored Nov 2, 2023
1 parent 36b4766 commit f7096aa
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 27 deletions.
Empty file added playground/.nuxt/tsconfig.json
Empty file.
48 changes: 35 additions & 13 deletions src/resolvers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync } from 'fs'
import { join, relative } from 'pathe'
import { addTemplate, createResolver, findPath, useNuxt, tryResolveModule } from '@nuxt/kit'
import { join, relative, resolve } from 'pathe'
import { addTemplate, createResolver, findPath, useNuxt, tryResolveModule, resolveAlias } from '@nuxt/kit'
import type { Arrayable, InjectPosition, ModuleOptions } from './types'

/**
Expand All @@ -22,17 +22,39 @@ export const resolveConfigPath = async (path: Arrayable<string>) => (
* @param srcDir
* @returns array of resolved content globs
*/
export const resolveContentPaths = (srcDir: string) => ([
`${srcDir}/components/**/*.{vue,js,ts}`,
`${srcDir}/layouts/**/*.vue`,
`${srcDir}/pages/**/*.vue`,
`${srcDir}/composables/**/*.{js,ts}`,
`${srcDir}/plugins/**/*.{js,ts}`,
`${srcDir}/utils/**/*.{js,ts}`,
`${srcDir}/{App,app}.{js,ts,vue}`,
`${srcDir}/{Error,error}.{js,ts,vue}`,
`${srcDir}/app.config.{js,ts}`
])
export const resolveContentPaths = (srcDir: string, nuxt = useNuxt()) => {
const r = (p: string) => p.startsWith(srcDir) ? p : resolve(srcDir, p)
const extensionFormat = (s: string[]) => s.length > 1 ? `.{${s.join(',')}}` : `.${s.join('') || 'vue'}`

const defaultExtensions = extensionFormat(['js', 'ts', 'mjs'])
const sfcExtensions = extensionFormat(nuxt.options.extensions.map(e => e.replace(/^\.*/, '')))

const importDirs = [...(nuxt.options.imports.dirs || [])].map(r)
const [composablesDir, utilsDir] = [resolve(srcDir, 'composables'), resolve(srcDir, 'utils')]

if (!importDirs.includes(composablesDir)) importDirs.push(composablesDir)
if (!importDirs.includes(utilsDir)) importDirs.push(utilsDir)

return [
...(() => {
if (nuxt.options.components) {
return (Array.isArray(nuxt.options.components) ? nuxt.options.components : typeof nuxt.options.components === 'boolean' ? ['components'] : nuxt.options.components.dirs).map(d => `${resolveAlias(typeof d === 'string' ? d : d.path)}/**/*${sfcExtensions}`)
}
return []
})(),

r(`${nuxt.options.dir.layouts}/**/*${sfcExtensions}`),
...(nuxt.options.pages ? [r(`${nuxt.options.dir.pages}/**/*${sfcExtensions}`)] : []),

r(`${nuxt.options.dir.plugins}/**/*${defaultExtensions}`),
r(`${nuxt.options.dir.modules}/**/*${defaultExtensions}`),
...importDirs.map(d => `${d}/**/*${defaultExtensions}`),

r(`{A,a}pp${sfcExtensions}`),
r(`{E,e}rror${sfcExtensions}`),
r(`app.config${defaultExtensions}`),
]
}

/**
*
Expand Down
35 changes: 26 additions & 9 deletions test/configs.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { describe, test, expect, vi } from 'vitest'
import { describe, test, expect, vi, afterAll } from 'vitest'
import { useTestContext } from '@nuxt/test-utils'
import destr from 'destr'
import { setupNuxtTailwind } from './util'
import { setupNuxtTailwind, r } from './util'
import { Config } from 'tailwindcss'

describe('tailwindcss module configs', async () => {
const spyStderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => undefined!)
Expand All @@ -22,6 +23,12 @@ describe('tailwindcss module configs', async () => {
'content-obj.config'
],
cssPath: 'tailwind.css'
},
{
dir: { plugins: 'my-pluggable-modules', modules: 'my-modular-plugins' },
modules: [r('modules/cjs-config.ts'), '@nuxtjs/tailwindcss'],
imports: { dirs: ['my-imports-dir1', 'my-imports-dir2'] },
extensions: ['.json', '.mdc', '.mdx', '.coffee']
})

test('throws error about malformed config', () => {
Expand All @@ -34,33 +41,43 @@ describe('tailwindcss module configs', async () => {

test('ts config file is loaded and merged', () => {
const nuxt = useTestContext().nuxt!
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('tailwind.config.'))!
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('test-tailwind.config.'))!
// set from ts-tailwind.config.ts
expect(nuxt.vfs[vfsKey]).contains('"typescriptBlue": "#007acc"')
})

test('js config file is loaded and merged', () => {
const nuxt = useTestContext().nuxt!
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('tailwind.config.'))!
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('test-tailwind.config.'))!
// set from ts-tailwind.config.ts
expect(nuxt.vfs[vfsKey]).contains('"javascriptYellow": "#f1e05a"')
})

test('content is adaptive', () => {
const nuxt = useTestContext().nuxt!
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('test-tailwind.config.'))!
const { content: { files } } = destr<Omit<Config, 'content'> & { content: Extract<Config['content'], { relative?: boolean }> }>(nuxt.vfs[vfsKey].replace(/^(module\.exports = )/, ''))

expect(files.find(c => /my-pluggable-modules|my-modular-plugins/.test(c))).toBeDefined()
expect(files.filter(c => c.includes('my-imports-dir')).length).toBe(2)
expect(files.find(c => c.includes('components/**/*'))?.includes('json,mdc,mdx,coffee')).toBeTruthy()
})

test('content is overridden', () => {
const nuxt = useTestContext().nuxt!
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('tailwind.config.'))!
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('test-tailwind.config.'))!
// set from override-tailwind.config.ts
const contentFiles = destr(nuxt.vfs[vfsKey].replace(/^(module\.exports = )/, '')).content.files
const contentFiles = destr<Omit<Config, 'content'> & { content: Extract<Config['content'], { relative?: boolean }> }>(nuxt.vfs[vfsKey].replace(/^(module\.exports = )/, '')).content.files

expect(contentFiles[0]).toBe('ts-content/**/*.md')
expect(contentFiles[1]).toBe('./custom-theme/**/*.vue')
expect(contentFiles.slice(2).filter(c => c.endsWith('vue')).length).toBe(2)
expect(contentFiles.filter(c => /{[AE],[ae]}/.test(c)).length).toBe(0)
})

test('content merges with objects', () => {
const nuxt = useTestContext().nuxt!
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('tailwind.config.'))!
const { content } = destr(nuxt.vfs[vfsKey].replace(/^(module\.exports = )/, ''))
const vfsKey = Object.keys(nuxt.vfs).find(k => k.includes('test-tailwind.config.'))!
const { content } = destr<Omit<Config, 'content'> & { content: Extract<Config['content'], { relative?: boolean }> }>(nuxt.vfs[vfsKey].replace(/^(module\.exports = )/, ''))

expect(content.relative).toBeTruthy()
expect(content.files.pop()).toBe('./my-components/**/*.tsx')
Expand Down
6 changes: 4 additions & 2 deletions test/fixture/basic/modules/cjs-config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { defineNuxtModule, addTemplate } from '@nuxt/kit'
import { defineNuxtModule, addTemplate, logger } from '@nuxt/kit'

Check warning on line 1 in test/fixture/basic/modules/cjs-config.ts

View workflow job for this annotation

GitHub Actions / ci (ubuntu-latest, 18)

'logger' is defined but never used

export default defineNuxtModule({
setup (_options, nuxt) {
// logger.info('Creating test-tailwind.config.cjs...')

nuxt.hook('tailwindcss:resolvedConfig', (config) => {
addTemplate({
filename: 'tailwind.config.cjs', // gets prepended by .nuxt/
filename: 'test-tailwind.config.cjs', // gets prepended by .nuxt/
getContents: () => `module.exports = ${JSON.stringify(config, null, 2)}`,
write: true
})
Expand Down
2 changes: 1 addition & 1 deletion test/fixture/basic/override-tailwind.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export default {
content: contentDefaults => [
contentDefaults[0],
'./custom-theme/**/*.vue',
...contentDefaults.filter(c => c.endsWith('vue'))
...contentDefaults.filter(c => !/{[AE],[ae]}/.test(c))
],
theme: {
extend: {
Expand Down
2 changes: 1 addition & 1 deletion test/fixture/basic/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
// https://nuxt.com/docs/guide/concepts/typescript
"extends": "./.nuxt/tsconfig.json"
"extends": "../../../playground/.nuxt/tsconfig.json"
}
5 changes: 4 additions & 1 deletion test/util.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { fileURLToPath } from 'node:url'
import { setup } from '@nuxt/test-utils'
import { NuxtConfig } from '@nuxt/schema'
import { ModuleOptions } from '../src/module'

export const r = (s: string = '') => fileURLToPath(new URL('./fixture/basic/' + s, import.meta.url))

export const setupNuxtTailwind = (tailwindcss = {}) => {
export const setupNuxtTailwind = (tailwindcss: Partial<ModuleOptions> = {}, nuxtConfig: NuxtConfig = {}) => {
return setup({
rootDir: r(),
server: true,
browser: false,
nuxtConfig: {
...nuxtConfig,
tailwindcss
}
})
Expand Down

0 comments on commit f7096aa

Please sign in to comment.