Import styles directly from tailwindCSS config file

Viewed 645

I have a react application built with create-react-app v5 and I am using tailwindCSS v3.

My project's root directory is "./src" and tailwindCSS configuration file is at "./" (one directory before src).

./tailwind.config.js

I'm trying to import the file using this:

theme.tsx file

//@ts-ignore
import resolveConfig from "tailwindcss/resolveConfig";
import tailwindConfig from "../tailwind.config.js";

const config = resolveConfig(tailwindConfig);
const theme: any = config.theme;
export default theme;

Since tailwindCSS v3, I can't move the tailwind config file from the root directory. The command above works but only if the file is inside "./src" and I can't place it there, so I get the following error:

Module not found: Error: You attempted to import ../tailwind.config.js which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

How can I import tailwindCSS styles directly from the config file? what I want to be able to do is to style elements without the classNames, I want to get the values directly from the config file in order to do something like this:

<div>
   <p style={{color: theme.colors.blue}}>Blue Text</p>
</div>

Is there a solution for this?

Thanks in advance

1 Answers

I faced the same issue. So, I created one more tailwind.config inside src and exported as module from there.

File structure:

tailwind.config.js

const tailwindConfig = require("./src/tailwind.config");

module.exports = tailwindConfig;

src/tailwind.config.js

module.exports = { 
  content: ['./src/**/*.{html,js}'],
  theme: {
    extend: {},
  },
  plugins: [],
}

src/tailwind-theme.js

import resolveConfig from "tailwindcss/resolveConfig";
const tailwindConfig = require("./tailwind.config");

const config = resolveConfig(tailwindConfig);
const theme = config.theme;
export default theme;

src/index.js

import theme from "tailwind-theme";

<div>
  <p style={{color: theme.colors.blue}}>Blue Text</p> 
</div>
Related