diff --git a/integrations/tailwindcss-cli/tests/cli.test.js b/integrations/tailwindcss-cli/tests/cli.test.js index 553097ce0208..f54e901ecfca 100644 --- a/integrations/tailwindcss-cli/tests/cli.test.js +++ b/integrations/tailwindcss-cli/tests/cli.test.js @@ -464,4 +464,62 @@ describe('Init command', () => { `) ) }) + + test('--help in ESM package', async () => { + let pkg = await readOutputFile('../package.json') + + await writeInputFile('../package.json', JSON.stringify({ + ...JSON.parse(pkg), + type: 'module', + })) + + let { combined } = await $(`${EXECUTABLE} init --help`) + + expect(dedent(combined)).toEqual( + dedent(` + tailwindcss v${version} + + Usage: + tailwindcss init [options] + + Options: + -f, --full Initialize a full \`tailwind.config.cjs\` file + -p, --postcss Initialize a \`postcss.config.cjs\` file + --types Add TypeScript types for the \`tailwind.config.cjs\` file + -h, --help Display usage information + `) + ) + + await writeInputFile('../package.json', pkg) + }) + + test('cjs config created when in ESM package', async () => { + cleanupFile('tailwind.config.cjs') + + let pkg = await readOutputFile('../package.json') + + await writeInputFile('../package.json', JSON.stringify({ + ...JSON.parse(pkg), + type: 'module', + })) + + let { combined } = await $(`${EXECUTABLE} init`) + + expect(combined).toMatchInlineSnapshot(` + " + Created Tailwind CSS config file: tailwind.config.cjs + " + `) + + expect(await fileExists('./tailwind.config.cjs')).toBe(true) + + // Not a clean way to test this. + expect(await readOutputFile('../tailwind.config.cjs')).toContain('module.exports =') + + expect(await readOutputFile('../tailwind.config.cjs')).not.toContain( + `/** @type {import('tailwindcss/types').Config} */` + ) + + await writeInputFile('../package.json', pkg) + }) }) diff --git a/src/cli.js b/src/cli.js index bbe3130496e5..98f26e109989 100644 --- a/src/cli.js +++ b/src/cli.js @@ -23,7 +23,21 @@ let env = { DEBUG: process.env.DEBUG !== undefined && process.env.DEBUG !== '0', } -let configs = { +function isESM() { + const pkgPath = path.resolve('./package.json') + + try { + let pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) + return pkg.type && pkg.type === 'module' + } catch (err) { + return false + } +} + +let configs = isESM() ? { + tailwind: 'tailwind.config.cjs', + postcss: 'postcss.config.cjs', +} : { tailwind: 'tailwind.config.js', postcss: 'postcss.config.js', }