Export project with Nextjs Tailwind Emotion loses tailwind css styles - next.js

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`)

Related

How can i apply tailwind css in app folder in Next 13

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

Tailwind css not working on route likes /api/user/forget/123/asddd

i have configure tailwind css and its working fine but when i give routes like api/user/forget/id/token then tailwind css not working on that route
my configuration
module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
theme: {
extend: {},
},
plugins: [],
}
how to get working tailwind classes on that type of route

After webpack(Nextjs 10 project) changes tailwind errors

Before the changes, everything was going to build and everything worked.
my next.config.js //
// const withCss = require('#zeit/next-css');
// const withSass = require('#zeit/next-sass');
class TailwindExtractor {
static extract(content) {
return content.match(/[A-Za-z0-9-_:\/]+/g) || [];
}
}
const nextConfig = {
...
};
module.exports = withPlugins([
// [ withSass, {} ],
// [ withCss, {} ],
[ withPurgeCss, {
...
}
], nextConfig);
Further, as recommended, I decided to abandon the use of the deprecated # zeit / next-css and # zeit / next-sass
I added the tailwind.config.js file as written on their website:
module.exports = {
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
};
And made changes to post.config.js and also installed the missing packages:
module.exports = {
plugins: {
'postcss-import': {},
tailwindcss: {},
autoprefixer: {},
'postcss-preset-env': { stage: 2 },
},
};
In _app.js, I include the main.scss file:
#import "tailwindcss/preflight";
#import "tailwindcss/components";
#import "tailwindcss/utilities";
.self-class {
#apply .bg-olive .shadow-olive .text-base .text-white .font-bold;
}
I get an error: Error: Syntax error: /home/roma/project/main.scss #applycannot be used with.bg-olivebecause.bg-oliveeither cannot be found, or its actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that.bg-oliveexists, make sure that any#importstatements are being properly processed *before* Tailwind CSS sees your CSS, as#apply can only be used for classes in the same CSS tree.
Do I have my tailwind.config.js file configured incorrectly or is the file built incorrectly in general? So where I am trying to refer to tailwind styles is not known about them yet?
Thanks for any help!

Tailwind css classes not showing in Storybook build

I am trying to build my storybook with tailwind css. When running build-storybook the components are rendered with the tailwind classes. Unfortunately, when I build storybook and run the create build storybook-static with npx http-server storybook-static the classes are not loaded into the stories and the components are displayed not styled.
This is a repro repo of my project:
https://gitlab.com/ens.evelyn.development/storybook-issue
This is my main.js :
const path = require('path')
module.exports = {
"stories": [
"../src/components/**/**/*.stories.mdx",
"../src/components/**/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
"#storybook/addon-actions",
"storybook-tailwind-dark-mode"
]}
My Projectstructure looks like this:
.storybook
src
components
subdir
Button
index.tsx
button.stories.js
styles
index.css (<-- tailwindcss file)
Any hints or advice is very appreciated.
UPDATE: My original answer could be useful to others, so I'll leave it for reference. However, in this case, the problem was in tailwind.config.js.
Change
purge: {
mode: 'all',
content: [
'./src/components/**/**/*.{ts, tsx}'
],
},
to
purge: ['./src/**/*.{js,jsx,ts,tsx}'],
ORIGINAL:
Just tested it out and storybook builds as expected for me. I think the key difference in our configurations is that I am not making changes to Storybook's webpack config in main.js. Rather, I am using #storybook/addon-postcss for postcss#^8 (required for tailwind#^2):
// main.js
module.exports = {
...
addons: [
...
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
],
};
I specify the necessary plugins in a postcss.config.js (in my project root):
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
It's also worth noting that I import Tailwind directly in Storybook's preview.js instead via my own css file:
// preview.js
import 'tailwindcss/tailwind.css';
export const parameters = {...}
Hopefully, making those changes will get Tailwind working for you.
For comparison (see comments below), here are the contents of my build storybook-static directory:
The above solutions will not work for Tailwind version > 3.0 because of JIT compiler.
Solution 1: Easy solution
in .storybook/preview.js file add this line to compile tailwind generated css files like this -
import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';
Here tailwindcss/tailwind.css is the tailwind css file. Look, important is I've to add !postcss-loader! to compile tailwind generated css.
You can add also your custom scss file like this if any -
import '!style-loader!css-loader!sass-loader!../src/scss/style.scss';
Here ../src/scss/style.scss is custom scss file.
For most of the people this will work in Tailwind version > 3.0 without any issue.
Solution 2: Kinda Hack solution
Create a custom styled element in preview page
import tailwindCss from '!style-loader!css-loader!postcss-loader!sass-loader!tailwindcss/tailwind.css';
const storybookStyles = document.createElement('style');
storybookStyles.innerHTML = tailwindCss;
document.body.appendChild(storybookStyles);
Hope, this will help for new Tailwind users who are working in Tailwind greater than v3.0.
I had a similar problem. My problem was solved by adding:
import "../src/index.css"; to .storybook/preview.js
The following configuration will enable so Tailwind generate CSS as new tailwind classes are added to the markup in dev mode (hot reload).
In summary, I don't think #storybook/addon-postcss works with Tailwind JIT and Storybook hot reload, and the workaround is to use the postcss-loader webpack loader.
Install these deps:
#storybook/builder-webpack5
#storybook/manager-webpack5
postcss-loader
webpack (must be version 5)
// .storybook/main.js
const path = require("path");
module.exports = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.#(js|jsx|ts|tsx)"],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions",
// {
// name: "#storybook/addon-postcss",
// options: {
// postcssLoaderOptions: {
// implementation: require("postcss"),
// },
// },
// },
],
framework: "#storybook/react",
core: {
builder: "webpack5",
},
webpackFinal: (config) => {
config.module.rules.push({
test: /\.css$/,
use: [
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [require("tailwindcss"), require("autoprefixer")],
},
},
},
],
include: path.resolve(__dirname, "../"),
});
return config;
},
};
// .storybook/preview.js
import "../styles/globals.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
if you using storybook with TSdx and tailwind css you should be able to import a CSS into components
To be able to import your CSS into components, you will need to tell
TSDX how to include it with your code. For that, you will need to
install rollup-plugin-postcss (as TSDX uses rollup).
Create a CSS file in your src directory which we will use in any
component in which we want to use Tailwind.
Alright, so now let's add rollup-plugin-postcss:
yarn add -D rollup-plugin-postcss
TSDX is fully customizable and you can add any rollup plugin, but be aware that it overrides the default behavior
Now you'll create a
tsdx.config.js
// tsdx.config.js
const postcss = require('rollup-plugin-postcss');
module.exports = {
rollup(config, options) {
config.plugins.push(
postcss({
config: {
path: './postcss.config.js',
},
extensions: ['.css'],
minimize: true,
inject: {
insertAt: 'top',
},
})
);
return config;
},
};
This is giving a postCSS path, which tells it what files you want it to run on. The minimize key is to allow you to minimize the output. The most important key here is the "inject". you set it to "top" to tell postCSS where inside the of our page the CSS will be inserted. It's paramount for Tailwind as it needs to have the utmost priority of any other stylesheet.
Next, for part 2, you will create a tailwind.css (can be named anything else) file under the src directory and paste this in:
// src/tailwind.css
#tailwind base;
#tailwind components;
#tailwind utilities;
Add the CSS import statement to your component
// src/Thing.tsx
import React, { FC, HTMLAttributes, ReactChild } from 'react';
// ! Add the CSS import statement !
import './tailwind.css`;
// ...
// we'll add some Tailwind classes on our components to test
export const Thing: FC<Props> = ({ children }) => {
return (
<div className="flex items-center justify-center w-5/6 m-auto text-2xl text-center text-pink-700 uppercase bg-blue-300 shadow-xl rounded-3xl">
{children || `the snozzberries taste like snozzberries`}
</div>
);
};
For those who are still having this problem and is using postcss >= 8, I suggest you to do as following.
Add this to tailwind.config.js
// eslint-disable-next-line #typescript-eslint/no-var-requires
const path = require("path")
module.exports = {
content: [path.join(__dirname, "./src/**/*.(js|jsx|ts|tsx)")],
theme: {
extend: {},
},
variants: {}
plugins: [],
}
Add this to preview.js
import "!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css"
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
}
This has helped me fix the problem and I hope it can help you too
I couldn't work this out and the above answered didn't work for me, so I eventually just set my build-storybook script to run tailwind itself after the build. package.json scripts looked like this in the end:
"build-storybook": "build-storybook -s public && $(npm bin -g)/tailwindcss -i storybook-static/static/css/main.*.chunk.css -o storybook-static/static/css/main.*.chunk.css -m",
Bit of a mess, but $(npm bin -g)/ here uses my globally installed (npm i -g tailwindcss) version of tailwindcss as the version installed to the project wasn't working in builds for me.
-i and -o specifies the input and output files, and -m minifies the output.
I can foresee this causing problems if more than one CSS file gets built (maybe using storybook-static/static/css/**/*.css would work instead?), but this might help someone just get something working.
When you try to create a storybook while using Tailwind CSS, you will notice that the CSS is not being applied. There is a simple solution that has helped me.
Your preview.js should be like.
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
And you will need to add the following line in the preview.js to fix it.
// Add the below import line
import "!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
However this will be a temporary fix.
To get this resolved completely, you will need to add the below mentioned package.
yarn add -D #storybook/addon-postcss
For reference, click here
How to add postcss
The solutions mentioned above worked but only partially.
I was facing 2 issues:
If I added new classes to stories then tailwind was not adding corresponding styles associated with the classes.
Hot reloading wasn't working.
Solution:
Add the path to the stories folder in the tailwind.config.js file.
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./stories/**/*.{js,ts,jsx,tsx}", //needed to make hot reload work with stories
],
theme: {},
plugins: [],
}

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: [],
}

Resources