How can i apply tailwind css in app folder in Next 13 - next.js

Tailwind CSS is not applying to the app folder in the next.js v13, but it is working on the Pages and Components folder.
In the tailwind.config file, I have added
However, no CSS is being applied to components in app folder!
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./app/**/*.{js,ts,jsx,tsx}",
],

try to check the following: (works for me)
in next.config.js
set experimental.appDir: true to enable app directory feature
const nextConfig = {
experimental: {
appDir: true,
},
}
in tailwind.config.js
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
...
}
in ./app/globals.css
#tailwind base;
#tailwind components;
#tailwind utilities;
in ./app/layout.tsx
import css in layout => works fine
import css in page => not working
import './globals.css';
...

Using tailwindcss with Nextjs 13 and Turbopack
Update dependencies
npm install -D tailwindcss postcss autoprefixer concurrently
npx tailwindcss init -p
Configuring tailwind.config.js
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}", // Note the addition of the `app` directory.
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Configuring next.config.js
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
experimental: {
appDir: true,
},
}
module.exports = nextConfig
Update package.json
// ...
"scripts": {
"dev": "concurrently \"next dev --turbo\" \"tailwindcss --input ./styles/input.css --output ./styles/output.css --watch\"",
"build": "tailwindcss ./styles/input.css --output ./styles/output.css && next build",
"start": "next start",
"lint": "next lint"
},
// ...
Create ./styles/input.css
#tailwind base;
#tailwind components;
#tailwind utilities;
Create empty ./styles/output.css file
Create ./app/layout.tsx
import "../styles/output.css";
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
Add styles to ./app/page.tsx
export default function Home() {
return (
<h1 className="m-12 text-4xl text-red-600">
Welcome to NextJS 13 with tailwindcss and turbopack
</h1>
);
}
Run project
npm run dev
References:
Tailwind CSS
Use Turbopack with TailwindCSS and Nextjs 13 today

I think #lorekkusu is right, but missed something.
Assuming I'm working on /app/blog/page.tsx, globals.css will be required to imported again, despite it was imported at /app/layout.tsx
import '../globals.css' //at /app/blog/page.tsx

Ah... Figured out the issue to resolve my comment.
In my case, I had to do an additional update to my next config because I am using Turborepo.
In NextJS 12, the following was what I had in my next.config.js
const withTM = require("next-transpile-modules")(["ui"]);
module.exports = withTM({
reactStrictMode: true,
experimental: { appDir: true }
});
However, I realized by spinning up a new turborepo from latest, that the way you transpile code has changed. This now also needs to be declared in the experimental block.
module.exports = {
reactStrictMode: true,
experimental: {
transpilePackages: ["ui"],
appDir: true
}
};
Once you do this, along with the listed steps in the nextjs documentation, you should be able to use tailwind in Next + Turborepo :)

Had the same problem.
I moved globals.css from /app to /styles, and then import in app/layout.tsx.
Now works fine.

You can follow this step:
Inside the root layout (app/layout.js), import the global.css stylesheet to apply the styles to every route in your application.

If you've selected the "use /src" option while installing nextjs then you need to have your tailwind.config.js configured as such:
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/app/**/*.{js,ts,jsx,tsx}',
'./src/pages/**/*.{js,ts,jsx,tsx}',
'./src/components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [],
}

Remember the moment you change your folder structure to /app style in Nextjs project you need to add this line into your
in tailwind.config.js
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}", // <-------------------
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
...
}
After that check following:
in next.config.js
const nextConfig = {
experimental: {
appDir: true,
},
}
in globals.css
#tailwind base;
#tailwind components;
#tailwind utilities;
And finally, where ever you are importing the globals.css
do it like:
import './globals.css';
You can refer to this documentation here.

Next config should be experimental
const nextConfig = {
reactStrictMode: true,
experimental: {
appDir: true,
},
}
You need to be add app directory for tailwind
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [
require('tailwind-scrollbar'),],
}
Globals.css
#tailwind base;
#tailwind components;
#tailwind utilities;
Most important step
import '../styles/globals.css'
if you are migrating to next 13 your globals.css should be in app directory after adding it. You can import it by this:
import './globals.css';

You need to follow the four steps
Install Tailwind CSS
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Change the config to root path or prefix /src folder
/* /tailwind.config.js */
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/app/**/*.{js,ts,jsx,tsx}',
'./src/pages/**/*.{js,ts,jsx,tsx}',
'./src/components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [],
};
Apply the tailwind to globals css /src/app/globals.css
/* /src/app/globals.css */
#tailwind base;
#tailwind components;
#tailwind utilities;
Configure PostCSS config file /postcss.config.js
// /postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

In my case I was making the pages like
src/pages/blog.jsx
It did render but tailwind wasn't working.
Then after reading the [Pages and Layout] docs for the app directory i moved it to src/app/blog/page.jsx
and now it works :D

Related

TailwindCSS not working in production - NEXT JS

I have made an app for production. During development I used tailwindcss with postcss and autoprefixer packages. Tailwindcss was working in development but when I deployed it to production it didn't worked. I tried to reinstall tailwind and other packages but still it didn't worked. I also tried to change path in tailwind.config.css file but still didn't worked. I don't know what I am doing wrong! Here is my config files of tailwindcss and postcss
I am using Heroku hosting
tailwindcss.config.js
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
};
postcss.config.js
module.exports = {
plugins: {
tailwindcss: { config: "./tailwind.config.js" },
autoprefixer: {},
},
};
Global Styles
#tailwind base;
#tailwind components;
#tailwind utilities;
Try this ..
const { join } = require('path');
module.exports = {
plugins: {
tailwindcss: {
config: join(__dirname, 'tailwind.config.js'),
},
autoprefixer: {},
},
};
and same for tailwind.config.js
important: true,
content: [join(__dirname, 'src/**/*.{js,jsx,ts,tsx,vue,html,css}')]
if it didnt work try alternative source
#config "./tailwindcss-config.js";
#tailwind base;
#tailwind components;
#tailwind utilities;

How to enable Tailwind.css for Storybook in a Nx workspace Angular library?

I've created an Angular library in Nx workspace to provide ui-components (ui-kit). To this library I added Storybook which was working fine. Now I also want to include Tailwind because the components make use of it.
I used the nx generate #nrwl/angular:setup-tailwind --project=ui-kit --buildTarget=build-storybook command to setup tailwind for that library. The library is buildable.
I have a tailwind.config.js which looks like this:
const { createGlobPatternsForDependencies } = require('#nrwl/angular/tailwind');
const { join } = require('path');
module.exports = {
content: [
join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html}'),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
extend: {},
},
plugins: [],
};
and added a tailwind-imports.css with content
#tailwind base;
#tailwind components;
#tailwind utilities;
as import to preview.js in the .storybook folder of the library.
But, no tailwind.
Is there any recipe to follow or some running example with nx, angular, storybook and tailwind?
Using nx version 13.8.3
Thanks so much for any help!
In project.json (inside your library), add 'styles' array to 'build-storybook' target:
"build-storybook": {
"executor": "#nrwl/storybook:build",
"outputs": ["{options.outputPath}"],
"options": {
"uiFramework": "#storybook/angular",
"outputPath": "dist/storybook/angular",
"styles": ["libs/<library_name>/src/styles.scss"], // <------ HERE
"config": {
"configFolder": "libs/<library_name>/.storybook"
},
"projectBuildConfig": "angular:build-storybook"
},
"configurations": {
"ci": {
"quiet": true
}
}
}
And inside styles.scss:
#tailwind base;
#tailwind components;
#tailwind utilities;
I have a React version working, I hope this helps.
Keep in mind that storybook requires a hard refresh for UI updates to be reflected as there is no hot-reloading out of the box.
We are going with the PostCSS version seen here.
You need the following files:
// libs/{app-name}/tailwind.config.js
const { createGlobPatternsForDependencies } = require('#nrwl/react/tailwind');
const { join } = require('path');
module.exports = {
content: [
join(__dirname, 'src/**/!(*.stories|*.spec).{ts,tsx,html}'),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
extend: {},
},
variants: {},
plugins: [],
};
// libs/{app-name}/postcss.config.js
const { join } = require('path');
module.exports = {
plugins: {
tailwindcss: {
config: join(__dirname, 'tailwind.config.js')
},
autoprefixer: {},
},
};
// libs/{app-name}/.storybook/main.js
const rootMain = require('../../../.storybook/main');
module.exports = {
...rootMain,
core: { ...rootMain.core, builder: 'webpack5' },
stories: [
...rootMain.stories,
'../src/lib/**/*.stories.mdx',
'../src/lib/**/*.stories.#(js|jsx|ts|tsx)',
],
addons: [...rootMain.addons, '#nrwl/react/plugins/storybook'],
webpackFinal: async (config, { configType }) => {
// apply any global webpack configs that might have been specified in .storybook/main.js
if (rootMain.webpackFinal) {
config = await rootMain.webpackFinal(config, { configType });
}
// add your own webpack tweaks if needed
return config;
},
};
// libs/{app-name}/.storybook/preview.js
import './tailwind-imports.css';
// libs/{app-name}/.storybook/tailwind-imports.css
#tailwind base;
#tailwind components;
#tailwind utilities;
Here is an article explaining how to do it: Set up Tailwind CSS and Storybook with Angular in an Nx workspace
Also, here's a sample repo, created by Leo from the Nx team.
add a styles.css file inside your .storybook folder in the library and make sure you have a tailwind.config.js in that lib too!
"storybook": {
"executor": "#nrwl/storybook:storybook",
"options": {
"styles": ["libs/shared/ui-components/.storybook/styles.css"],
"uiFramework": "#storybook/angular",
"port": 4400,
"config": {
"configFolder": "libs/shared/ui-components/.storybook"
},
"projectBuildConfig": "shared-ui-components:build-storybook"
},
"configurations": {
"ci": {
"quiet": true
}
}
}
in the styles.css file you write:
#tailwind base;
#tailwind components;
#tailwind utilities;

Export project with Nextjs Tailwind Emotion loses tailwind css styles

I'm starting a new Next.js project that has existing emotion.js styles, now I'm trying to add tailwind, via this instruction https://tailwindcss.com/docs/guides/nextjs
Here is my postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
and tailwind.config.js
module.exports = {
purge: [
'./pages/**/*.js',
'./components/**/*.js',
'./lib/**/*/js'
],
darkMode: 'class', // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: []
}
and next.config.js
module.exports = {
images: {
domains: [
'user-images.githubusercontent.com'
]
},
typescript: {
ignoreBuildErrors: true
},
eslint: {
ignoreDuringBuilds: true
}
}
Here is how I use Tailwind in /styles/global.css
#tailwind base;
#tailwind components;
#tailwind utilities;
and include that css in /pages/_app.js
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
All styles look OK when I run next dev, but when I do next build && next export, it exports to /out folder but when I try running index.html it has no tailwind styles, however my emotion.js styles are still working.
I've tried searching all answers here about this but none of them work.
I suspect it has to do with conflicts with emotion.js with instruction like jsxImportSource
Here is how I use emotion.js. It runs fine during development though
/** #jsxImportSource #emotion/react */
import { useState, useEffect } from 'react';
import { css, jsx } from '#emotion/react'
function App() {
}
After checking the generated out/index.html I found out that the stylesheet has an absolute link, changing it to a relative link fixes the issue.
Change from
<link rel="preload" href="/_next/static/css/c8843280217d36ba4773.css"
to
<link rel="preload" href="./_next/static/css/c8843280217d36ba4773.css"
Not sure what it is this way, there seems to be discussion about Use relative URLs instead of absolute but for now I make a custom script that auto-update the link to be a relative path
htmlContent
.replace('link rel="stylesheet" href="/_next/static', `link rel="stylesheet" href="./_next/static`)

Vite does not build tailwind based on config

I created a new react-ts app using yarn create #vitejs/app my-app --template react-ts.
I installed tailwind using yarn add --dev tailwindcss#latest postcss#latest autoprefixer#latest.
I initialized tailwind: npx tailwindcss init -p.
I set from and to in postcss.config.js:
module.exports = {
from: 'src/styles/App.css',
to: 'src/styles/output.css',
plugins: {
tailwindcss: {},
autoprefixer: {}
}
}
I created a App.css file in src/styles:
#tailwind base;
#tailwind components;
#tailwind utilities;
According to https://vitejs.dev/guide/features.html#postcss, any valid postcss-load-config syntax is allowed. from and to seem to be allowed.
When I call yarn dev which essentially runs vite, my app is starting without build errors but tailwind output is not generated.
What am I doing wrong?
make sure your postcss.config.js file is in your app root directory
it solved my problem
tailwind.config.js
const defaultTheme = require('tailwindcss/defaultTheme')
module.exports = {
mode: 'jit',
purge: {
enabled: process.env.NODE_ENV === 'production',
// classes that are generated dynamically, e.g. `rounded-${size}` and must
// be kept
safeList: [],
content: [
'./index.html',
'./src/**/*.{vue,js,ts}',
// etc.
],
},
theme: {
extend: {
fontFamily: {
sans: ['Inter var', ...defaultTheme.fontFamily.sans],
},
},
},
}
In your vite.config.js, make sure to include Tailwind in your plugins.
plugins: [react(),tailwindcss()],
Also, you can import Tailwind with the following.
import tailwindcss from 'tailwindcss';
from and to are not required.
I had to update my import statement for the css file in main.tsx to point to src/styles/App.css which will cause vite to run postcss.
Maybe you are forget to fill content object in tailwind config
module.exports = {
content: ['./src/*.{js,jsx}', './src/**/*.{js,jsx}'],
theme: {
extend: {},
},
plugins: [],
}

How to get Tailwind's built-in CSS Purge to purge plugin CSS

I'm including Tailwind CSS in my project using PostCSS, and have Tailwind's built-in Purge implementation working great for the core library (in style.pcss below). However, I am also including #tailwind/typography as a plugin and its selectors aren't being purged.
// postcss.config.js
const cssnano = require('cssnano')
module.exports = {
plugins: [
require('postcss-import'),
require('tailwindcss'),
process.env.NODE_ENV === 'production' ? require('autoprefixer') : null,
process.env.NODE_ENV === 'production' ? cssnano({ preset: 'default' }) : null
]
}
// tailwind.config.js
module.exports = {
plugins: [
require('#tailwindcss/typography')
],
purge: [
'./build/*.html',
'./build/**/*.html'
],
}
// style.pcss
#tailwind base;
#tailwind components;
#tailwind utilities;
I Ran into the same thing!
There is a note about this on the typography README:
https://github.com/tailwindlabs/tailwindcss-typography#purging-unused-styles
...and more details in the tailwindscss documentation:
https://tailwindcss.com/docs/controlling-file-size#removing-all-unused-styles
Here is what your tailwind.config.js should probably look like:
module.exports = {
plugins: [
require('#tailwindcss/typography')
],
purge: {
enabled: true,
mode: 'all',
content: [
'./build/*.html',
'./build/**/*.html'
],
options: {
whitelist: []
}
},
}

Resources