6

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

2

1 Answer 1

8

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I have issue with TS: Trying to print colors with "console.log(theme?.colors?.blue)" it did logged but I got error: Property 'blue' does not exist on type 'ResolvableTo<RecursiveKeyValuePair<string, string>>'. Property 'blue' does not exist on type '(utils: PluginUtils) => RecursiveKeyValuePair<string, string>'.ts(2339)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.