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

Add TypeScript types for the tailwind.config.js file #7891

Merged
merged 9 commits into from
Mar 22, 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Support customizing class name when using `darkMode: 'class'` ([#5800](https://github.com/tailwindlabs/tailwindcss/pull/5800))
- Add `--poll` option to the CLI ([#7725](https://github.com/tailwindlabs/tailwindcss/pull/7725))
- Add new `border-spacing` utilities ([#7102](https://github.com/tailwindlabs/tailwindcss/pull/7102))
- Add TypeScript types for the `tailwind.config.js` file ([#7891](https://github.com/tailwindlabs/tailwindcss/pull/7891))

## [3.0.23] - 2022-02-16

Expand Down
3 changes: 3 additions & 0 deletions colors.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import type { DefaultColors } from './types/generated/colors'
declare const colors: DefaultColors
export = colors
3 changes: 3 additions & 0 deletions defaultConfig.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import type { Config } from './types/config'
declare const config: Config
export = config
3 changes: 3 additions & 0 deletions defaultTheme.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import type { Config } from './types/config'
declare const theme: Config['theme']
export = theme
41 changes: 41 additions & 0 deletions integrations/tailwindcss-cli/tests/cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,46 @@ describe('Init command', () => {
// multiple keys in `theme` exists. However it loads `tailwindcss/colors`
// which doesn't exists in this context.
expect((await readOutputFile('../full.config.js')).split('\n').length).toBeGreaterThan(50)

expect(await readOutputFile('../full.config.js')).not.toContain(
`/** @type {import('tailwindcss/types').Config} */`
)
})

test('--types', async () => {
cleanupFile('simple.config.js')

let { combined } = await $(`${EXECUTABLE} init simple.config.js --types`)

expect(combined).toMatchInlineSnapshot(`
"
Created Tailwind CSS config file: simple.config.js
"
`)

expect(await readOutputFile('../simple.config.js')).toContain(
`/** @type {import('tailwindcss/types').Config} */`
)
})

test('--full --types', async () => {
cleanupFile('full.config.js')

let { combined } = await $(`${EXECUTABLE} init full.config.js --full --types`)

expect(combined).toMatchInlineSnapshot(`
"
Created Tailwind CSS config file: full.config.js
"
`)

// Not a clean way to test this. We could require the file and verify that
// multiple keys in `theme` exists. However it loads `tailwindcss/colors`
// which doesn't exists in this context.
expect((await readOutputFile('../full.config.js')).split('\n').length).toBeGreaterThan(50)
expect(await readOutputFile('../full.config.js')).toContain(
`/** @type {import('tailwindcss/types').Config} */`
)
})

test('--postcss', async () => {
Expand Down Expand Up @@ -351,6 +391,7 @@ describe('Init command', () => {
Options:
-f, --full Initialize a full \`tailwind.config.js\` file
-p, --postcss Initialize a \`postcss.config.js\` file
--types Add TypeScript types for the \`tailwind.config.js\` file
-h, --help Display usage information
`)
)
Expand Down
12 changes: 8 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "A utility-first CSS framework for rapidly building custom user interfaces.",
"license": "MIT",
"main": "lib/index.js",
"style": "dist/tailwind.css",
"types": "types/index.d.ts",
"repository": "https://github.com/tailwindlabs/tailwindcss.git",
"bugs": "https://github.com/tailwindlabs/tailwindcss/issues",
"homepage": "https://tailwindcss.com",
Expand All @@ -13,18 +13,20 @@
"tailwindcss": "lib/cli.js"
},
"scripts": {
"preswcify": "npm run generate:plugin-list && rimraf lib",
"preswcify": "npm run generate && rimraf lib",
"swcify": "swc src --out-dir lib --copy-files",
"postswcify": "esbuild lib/cli-peer-dependencies.js --bundle --platform=node --outfile=peers/index.js",
"rebuild-fixtures": "npm run swcify && node -r @swc/register scripts/rebuildFixtures.js",
"prepublishOnly": "npm install --force && npm run swcify",
"style": "eslint .",
"pretest": "npm run generate:plugin-list",
"pretest": "npm run generate",
"test": "jest",
"test:integrations": "npm run test --prefix ./integrations",
"install:integrations": "node scripts/install-integrations.js",
"posttest": "npm run style",
"generate:plugin-list": "node -r @swc/register scripts/create-plugin-list.js"
"generate:plugin-list": "node -r @swc/register scripts/create-plugin-list.js",
"generate:types": "node -r @swc/register scripts/generate-types.js",
"generate": "npm run generate:plugin-list && npm run generate:types"
},
"files": [
"src/*",
Expand All @@ -34,6 +36,8 @@
"scripts/*.js",
"stubs/*.stub.js",
"nesting/*",
"types/**/*",
"*.d.ts",
"*.css",
"*.js"
],
Expand Down
6 changes: 6 additions & 0 deletions plugin.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { Config, PluginCreator } from './types/config'
declare function createPlugin(
plugin: PluginCreator,
config?: Config
): { handler: PluginCreator; config?: Config }
export = createPlugin
52 changes: 52 additions & 0 deletions scripts/generate-types.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import prettier from 'prettier'
import { corePlugins } from '../src/corePlugins'
import colors from '../src/public/colors'
import fs from 'fs'
import path from 'path'

fs.writeFileSync(
path.join(process.cwd(), 'types', 'generated', 'corePluginList.d.ts'),
`export type CorePluginList = ${Object.keys(corePlugins)
.map((p) => `'${p}'`)
.join(' | ')}`
)

let colorsWithoutDeprecatedColors = Object.fromEntries(
Object.entries(Object.getOwnPropertyDescriptors(colors))
.filter(([_, { value }]) => {
return typeof value !== 'undefined'
})
.map(([name, definition]) => [name, definition.value])
)

let deprecatedColors = Object.entries(Object.getOwnPropertyDescriptors(colors))
.filter(([_, { value }]) => {
return typeof value === 'undefined'
})
.map(([name, definition]) => {
let warn = console.warn
let messages = []
console.warn = (...args) => messages.push(args.pop())
definition.get()
console.warn = warn
let message = messages.join(' ').trim()
let newColor = message.match(/renamed to `(.*)`/)[1]
return `/** @deprecated ${message} */${name}: DefaultColors['${newColor}'],`
})
.join('\n')

fs.writeFileSync(
path.join(process.cwd(), 'types', 'generated', 'colors.d.ts'),
prettier.format(
`export interface DefaultColors { ${JSON.stringify(colorsWithoutDeprecatedColors).slice(
1,
-1
)}\n${deprecatedColors}\n}`,
{
semi: false,
singleQuote: true,
printWidth: 100,
parser: 'typescript',
}
)
)
13 changes: 12 additions & 1 deletion src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ let commands = {
args: {
'--full': { type: Boolean, description: 'Initialize a full `tailwind.config.js` file' },
'--postcss': { type: Boolean, description: 'Initialize a `postcss.config.js` file' },
'--types': {
type: Boolean,
description: 'Add TypeScript types for the `tailwind.config.js` file',
},
'-f': '--full',
'-p': '--postcss',
},
Expand Down Expand Up @@ -209,7 +213,7 @@ if (
help({
usage: [
'tailwindcss [--input input.css] [--output output.css] [--watch] [options...]',
'tailwindcss init [--full] [--postcss] [options...]',
'tailwindcss init [--full] [--postcss] [--types] [options...]',
],
commands: Object.keys(commands)
.filter((command) => command !== 'build')
Expand Down Expand Up @@ -336,6 +340,13 @@ function init() {
'utf8'
)

if (args['--types']) {
let typesHeading = "/** @type {import('tailwindcss/types').Config} */"
stubFile =
stubFile.replace(`module.exports = `, `${typesHeading}\nconst config = `) +
'\nmodule.exports = config'
}

// Change colors import
stubFile = stubFile.replace('../colors', 'tailwindcss/colors')

Expand Down
1 change: 1 addition & 0 deletions types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type { Config } from './types/config'
Loading