lobo_tuerto's notes
Home
Blog
Notes
About

Import tailwind.config.cjs in Vite

Vite is ESM only, how do we import CommonJS files in it?

📅Published17 September 2022
🏷️
frontendtailwindcsstypescriptvitevue 3

Let’s say you have a brand new Vue 3 + Vite project. You add Tailwind CSS to it and now you want to reference the config values inside a component.

Our goal will be to console.log(twConfig) to be able to browse the values in the console.

Easy enough, there seems to be some documentation for that right there in the official docs: Tailwind CSS - Referencing in JavaScript

There is a problem though. Let’s follow the instructions, add this to your src/App.vue file:

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from '../tailwind.config.cjs'

const twConfig = resolveConfig(tailwindConfig)

console.log('twConfig', twConfig)

Refresh and you’ll be presented with a cryptic:

Uncaught SyntaxError: import not found: default

What we need is to teach Vite how to import the tailwind.config.cjs which is a CommonJS file.

There are three parts to this: build, optimizeDeps and resolve.

In your vite.config.ts:

export default defineConfig({
  build: {
    commonjsOptions: {
      include: ['tailwind-config.cjs', 'node_modules/**'],
    },
  },

  optimizeDeps: {
    include: ['tailwind-config'],
  },

  plugins: [vue()],

  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      'tailwind-config': path.resolve(__dirname, './tailwind.config.cjs'),
    },
  },

  test: {
    environment: 'happy-dom',
    globals: true,
  },
})

An important change is the alias we’ve just created, it affects how we’ll import the config file now:

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from 'tailwind-config' // <- This!

const twConfig = resolveConfig(tailwindConfig)

console.log('twConfig', twConfig)

The code in you src/App.vue file will run OK in dev and build without issues for prod. 🎉

By the way, if you see an error like this when building your app:

error TS2307: Cannot find module 'tailwind-config' or its corresponding type declarations.

Just add this at the end of your src/vite-env.d.ts file:

declare module 'tailwind-config' {
  const config: Config
  export default config
}
Note
You should also consider if you really need this in your code base, because the build size goes up by 100KiB approx —before gzip.

References


Got comments or feedback?
Follow me on
v-24390d0