Yarn Compile error with tailwind.config.js

Hi Everyone,
I have a weird problem with any fresh “Sage” project i start.
If i tried to add any “Plugins” in the plugins array i have that error when trying to compile assets “yarn build”

That happens only when “tailwind.config.js” has the extension “.js”, if i switched it to “.cjs” everything works.
I want to follow the sage’s procedure because they added the “tailwind.config” with “.js” extension.

Anyone have any idea how can i solve that?

Sage version: 10.6

Error:

[fs] [tailwind.config.js] › :warning: tailwind.config.js causes an exception when imported.
Since tailwind.config.js does not appear to be a bud configuration file, bud.js is not throwing. Original error follows:

BudError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a ‘.js’ file extension and ‘package.json’ contains “type”: “module”. To treat it as a CommonJS script, rename it to use the ‘.cjs’ file extension.

tailwind.config.js
image

Package.json

Take a look at this summary of .mjs and .cjs file extensions.

You’re using require(), ie. CommonJS, but because your package.json has "type": "module" set, any .js file is loaded as an ES module, not CommonJS.

Either:

  • Change the extension to .cjs use CommonJS, or
  • Remove type: module from package.json

I’d recommend changing the extension, so other JS files in your project are still treated as ES modules.

Thanks for your reply, i actually tried to delete “type: module” but it affected other JS files, so I’ll change the extension to be more compatible.

I’d recommend keeping the .js extension and “use import instead” per the error message.

  1. Import the typography plugin at the top of the file using the ESM syntax:
import typography from '@tailwindcss/typography';
  1. Add the typography plugin to the plugins array in your config file:
module.exports = {
  // ...
  plugins: [
    // ...
    typography,
  ],
};
4 Likes

An alternative is to add the require function to ESM:

import {createRequire} from 'node:module';
const require = createRequire(import.meta.url);

What’s the benefit of doing this? This is confusing because you’re mixing ESM and CommonJS. The JS ecosystem is adopting ESM, and it makes sense to encourage the use of ESM imports where possible.

Just import modules the straightforward ESM way.