Tailwind.config.js and require vs import / ESM

Has anybody figured out how to replace old require statements with ES imports?

For example:

/** @type {import('tailwindcss').Config} config */

// How to replace defaultTheme require?
const defaultTheme = import('tailwindcss').defaultTheme

const config = {
	theme: {
		extend: {
			fontFamily: {
				sans: ['Raleway', ...defaultTheme.fontFamily.sans],
			},

// How to replace plugin require?

plugins: [
  require('@tailwindcss/forms'),

  // Custom variants
   require("./resources/tailwind/variants/parent-active-c"),

ReferenceError: require is not defined in ES module scope, you can use import instead

The output says to replace .js files with .cjs but that causes all kinds of headaches.

Converting all of my old plugins for imports is a massive pain too. The tailwind docs don’t seem to be compatible with the way sage / bud loads tailwind.config.js.

Is it possible to load Tailwind without ES modules?

Thanks

ReferenceError: require is not defined in ES module scope, you can use import instead

Per the error, you can use import :cowboy_hat_face:

Ignoring your customizations you’ve already made to the Tailwind config, this is what a default Sage 10 install’s Tailwind config would look like for handling the forms plugin:

import forms from '@tailwindcss/forms';

/** @type {import('tailwindcss').Config} config */
const config = {
  content: ['./app/**/*.php', './resources/**/*.{php,vue,js}'],
  theme: {
    extend: {
      colors: {}, // Extend Tailwind's default colors
    },
  },
  plugins: [
    forms, // Use the imported forms plugin here
  ],
};

export default config;

You should be able to follow the example above, and in the other topic you came from, to work with other plugins as well

It’s definitely a headache figuring this out for the first time when coming from CJS.

Hopefully it won’t be too much of a pain once you start getting the hang of it. GPT is also great at handling tasks like this.

It’s a bit surprising that Tailwind docs still haven’t accounted for folks using ESM, but I’d be willing to bet that will change in the upcoming v4 release.

Thanks for getting back to me.

It turns out I was just missing a couple of minor things.

Sometimes you have to use .js extension when importing:

  • This works for the forms plugin
    import forms from '@tailwindcss/forms';
  • But you have to use .js for defaultTheme
    import defaultTheme from 'tailwindcss/defaultTheme.js';

In my custom plugins I have to write them like this:

// .js extension required
import plugin from 'tailwindcss/plugin.js';

// used to be module.exports but now:
export default plugin(function ({ addUtilities }) {
	const utils = {
		'.w-edge': {
			position: 'relative',
			margin: '0 auto',
			width: '100vw',
			left: '50%',
			transform: 'translateX(-50%)'
		}
	}

  addUtilities(utils, ["responsive"])
})
2 Likes