nx - tailwindcss not working with next js - tailwind-css

I Generate a new project with nx using nextjs preset. Then with the help of the nx dev blog post i setup tailwind css like following
postcss.config.js
const { join } = require('path');
module.exports = {
plugins: {
tailwindcss: { config: './apps/storefront/tailwind.config.js' },
// tailwindcss: {
// config: join(__dirname, 'tailwind.config.js'),
// },
autoprefixer: {},
},
}
tailwind.config.js
const { createGlobPatternsForDependencies } = require('#nrwl/react/tailwind');
module.exports = {
purge: createGlobPatternsForDependencies(__dirname),
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
};
next.config.js
// eslint-disable-next-line #typescript-eslint/no-var-requires
const withNx = require('#nrwl/next/plugins/with-nx');
/**
* #type {import('#nrwl/next/plugins/with-nx').WithNxOptions}
**/
const nextConfig = {
nx: {
// Set this to true if you would like to to use SVGR
// See: https://github.com/gregberge/svgr
svgr: false,
},
};
module.exports = withNx(nextConfig);
But now if I run the apps, tailwind CSS does not seem to be laded in the app. So what am I doing wrong, and how can fix the issue?

In tailwind.config.js, you should change "purge" into "content" which recommends by the new release version of tailwindcss and also the path should config by starting from the root path. For example: content: ['./apps/blogs/pages/**/*.{js,ts,jsx,tsx}']

YR007 answer should be marked as the correct one, both postcss.config.js and tailwind.config.js should have root references if they are inside a monorepo app, for example:
postcss.config.js
module.exports = {
plugins: {
'tailwindcss/nesting': {},
tailwindcss: { config: './apps/backoffice/tailwind.config.js' },
autoprefixer: {},
},
};
tailwind.config.js
module.exports = {
content: [
'./apps/backoffice/index.html',
'./apps/backoffice/src/**/*.{vue,js,ts,jsx,tsx}',
],
darkMode: 'class',
theme: {
extend: {},
},
plugins: [],
};

**In Nx + Nextjs with tailwind some libs components are missing tailwindcss classes you can configure them like that in tailwind.config.js in Nextjs project **
you can point directly to libary
module.exports = {
content: [
join(__dirname, '**/*.{js,ts,jsx,tsx}'),
join('libs/ui/src/lib/**/*.{js,ts,jsx,tsx}'),
...createGlobPatternsForDependencies(__dirname),
],
}

There is a simple way for it's setup. Make a tailwind.config.js file at root and add this code
module.exports = {
mode: "jit",
purge: [
"./pages/**/*.{js,ts,jsx,tsx}",
],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
};
Create a postcss.config.js file and make this
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Then in your globals.css , simply import tailwind
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";
and include this globals.css file in your app.js

Related

Tailwindcss #apply is not working in storybook

I am using Next css modules (sass). I tried every solutions I've encountered but I still cannot get it working.
My problem is, when I run the storybook, the css doesn't compile #apply method from tailwind. There is a simple solution which is remove the #apply and use the classname directly to the element but I don't have the time to do because the application is too big at this point.
// main.js
const path = require('path');
module.exports = {
stories: [
'../stories/**/*.stories.mdx',
'../stories/**/*.stories.#(js|jsx|ts|tsx)',
],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
postcssOptions: {
plugins: [require.resolve('tailwindcss')],
},
implementation: require('postcss'),
},
},
},
],
framework: '#storybook/react',
webpackFinal: async (config) => {
config.module.rules.push({
test: /\.sass$/,
use: ['style-loader', 'css-loader?modules&importLoaders', 'sass-loader'],
include: path.resolve(__dirname, '../'),
});
return config;
},
};
output in storybook
Any help would be appreciated
I managed to make it work by using this config.
.storybook/main.js
const path = require('path');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
stories: [
'../stories/**/*.stories.mdx',
'../stories/**/*.stories.#(js|jsx|ts|tsx)',
],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
'storybook-addon-next-router',
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
postcssOptions: {
plugins: [require.resolve('tailwindcss')],
},
implementation: require('postcss'),
},
},
},
],
framework: '#storybook/react',
webpackFinal: async (config) => {
config.resolve.plugins.push(new TsconfigPathsPlugin());
config.module.rules.push({
test: /\.sass$/,
use: ['style-loader', 'css-loader?modules&importLoaders', 'sass-loader'],
include: path.resolve(__dirname, '../'),
});
return config;
},
};
.storybook/preview.js
import '../styles/globals.css';
import { RouterContext } from 'next/dist/shared/lib/router-context';
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
nextRouter: {
Provider: RouterContext.Provider,
},
};
In global.css, I imported the tailwind utilities
global.css
#tailwind base;
#tailwind components;
#tailwind utilities;

Nextjs config with postcss nesting doesn't work

I am using nextjs with tailwindcss and i am facing the difficulty in adding postcss-nesting to my nextjs app.
Here is the configuration below for the same :
next.config.js
const withPlugins = require("next-compose-plugins");
module.exports = withPlugins([], {});
postcss.config.js
module.exports = {
plugins: [
"postcss-import",
"tailwindcss",
"autoprefixer",
"tailwindcss/nesting",
"postcss-nested",
],
};
tailwind.config.js
module.exports = {
purge: {
enabled: true,
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./src/components/**/*.{js,ts,jsx,tsx}",
],
},
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
};
In my custom css file i am trying to use it like
.toolbar_navigation_items {
li {
#apply text-3xl;
}
}
then i am getting the error
"(2:3) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin *before* Tailwind in your configuration.
NOTE : I also tried changing my postcss.config.js to
module.exports = {
plugins: [
require('postcss-import'),
require('tailwindcss/nesting'),
require('tailwindcss'),
require('autoprefixer'),
]
}
as mentioned in the docs but it says
A PostCSS Plugin was passed as a function using require(), but it must be provided as a string.
I had same issue
install postcss-nesting: npm install -D postcss-nesting
postcss.config.js:
module.exports = {
plugins: {
"tailwindcss/nesting": "postcss-nesting",
tailwindcss: {},
autoprefixer: {},
},
};
https://tailwindcss.com/docs/using-with-preprocessors#nesting
Had same error. When used:
module.exports = {
plugins: [
require('postcss-import'),
require('tailwindcss/nesting'),
require('tailwindcss'),
require('autoprefixer'),
]
}
Got this link: https://nextjs.org/docs/messages/postcss-shape
It shows how new config should be written (remove the require('package') function wrapping the strings). New postcss.config.js:
module.exports = {
plugins: [
'postcss-import',
'tailwindcss/nesting',
'tailwindcss',
'autoprefixer',
]
}
This fixed the nesting config issue for me.
Quote:
npm i sharp
# or
yarn add sharp
https://nextjs.org/docs/messages/install-sharp

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!

Trouble with Typekit fonts in Tailwind

I'm trying to import TypeKit fonts into my Tailwind config. I have included the .css file like so in my index: https://use.typekit.net/kcz3fka.css. Inside my tailwind.config.cjs file I have the definition:
module.exports = {
purge: ['index.html', 'src/**/*.tsx'],
mode: 'jit',
theme: {
extend: {
container: {
center: true,
},
fontFamily: {
display: ['"katarine-web"', ...theme.fontFamily.sans],
body: ['"katarine-web"', ...theme.fontFamily.sans],
},
},
},
plugins: [
require('#tailwindcss/typography'),
require('#tailwindcss/aspect-ratio'),
],
};
I've tried escaping the katarine name as well as with and without double quotes. Neither seem to work as expected. What should I be doing to ensure Katarine can be used?
try this,
module.exports = {
purge: ['index.html', 'src/**/*.tsx'], // include your purge target files
mode: 'jit',
theme: {
extend: {
container: {
'center': true,
},
fontFamily: { // if you want extend 'katrarine-web', then just add them instead other originals.
'display': ['katarine-web'],
'body': ['katarine-web'],
},
},
},
plugins: [
require('#tailwindcss/typography'),
require('#tailwindcss/aspect-ratio'),
],
};
also, check this Doc.
Happy coding :)

NextJS with global CSS import fail in production mode

I'm using Next.JS with a few other modules. One of them, Megadraft, comes with its own CSS. I don't know if this is relevant, but I also use PurgeCSS.
Everything works fine on development mode, but the CSS seems to break in production mode. To be a little more explicit, all of the classes of Megadraft, seem to have no definition in production mode.
The HTML nodes in the inspector still show that the classes are here, but they have just no definition.
Here's how I import the said CSS files in my pages/_app.js file:
// pages/_app.js
import "css/tailwind.css";
import "megadraft/dist/css/megadraft.css";
And this is my postcss.config.js:
// postcss.config.js
const purgecss = [
"#fullhuman/postcss-purgecss",
{
content: [
"./components/**/*.js",
"./Layout/**/*.js",
"./pages/**/*.js",
"./node_modules/next/dist/pages/**/*.js",
"./node_modules/next/dist/Layout/**/*.js",
"./node_modules/next/dist/components/**/*.js"
],
defaultExtractor: (content) => content.match(/[A-Za-z0-9-_:/]+/g) || [],
},
];
module.exports = {
plugins: [
"postcss-import",
"tailwindcss",
"autoprefixer",
...(process.env.NODE_ENV === "production" ? [purgecss] : []),
],
};
I'm using next ^9.4.4. It may be worth noticing that TailwindCSS seems to work just fine (both in dev and prod), but I think it may be because it is used as a plugin in postcss...
Just in case also, I integrated webpack to my project to solve an error I had where the code was telling that I needed a loader:
// next.config.js
module.exports = {
cssModules: true,
webpack: (config, options) => {
config.node = {
fs: "empty",
};
config.module.rules.push({
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
use: [
options.defaultLoaders.babel,
{
loader: "url-loader?limit=100000",
},
{
loader: "file-loader",
},
],
});
return config;
},
};
Anyway, if someone has an idea of why this works in development mode and not in production, it could be of great help.
Option 1: use Tailwind CSS built-in PurgeCSS
// tailwind.config.css
module.exports = {
purge: ["./components/**/*.js", "./pages/**/*.js"],
theme: {
extend: {}
},
variants: {},
plugins: []
};
// postcss.config.js
module.exports = {
plugins: ["tailwindcss", "postcss-preset-env"]
};
Be sure to add postcss-preset-env to the package's dev dependencies with npm i --save-dev postcss-preset-env or yarn add -D postcss-preset-env.
Option 2: Manually setup purge and add "./node_modules/megadraft/dist/**/*.css" to purgecss whitelisting content array:
// tailwind.config.css
module.exports = {
theme: {
extend: {}
},
variants: {},
plugins: []
};
// postcss.config.js
const purgecss = ['#fullhuman/postcss-purgecss',{
content: ["./node_modules/megadraft/dist/**/*.css", "./components/**/*.js", "./pages/**/*.js"],
defaultExtractor: content => {
const broadMatches = content.match(/[^<>"'`\s]*[^<>"'`\s:]/g) || []
const innerMatches = content.match(/[^<>"'`\s.()]*[^<>"'`\s.():]/g) || []
return broadMatches.concat(innerMatches)
}
}]
module.exports = {
plugins: [
'tailwindcss',
'autoprefixer',
...process.env.NODE_ENV === 'production'
? [purgecss]
: []
]
}
There may be better solutions but these two are what I can think of.

Resources