Tailwindcss #apply is not working in storybook - next.js

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;

Related

webpack-5 tailwindcss set up is not working

this is tailwind.config.js
module.exports = {
// webpack is building into dist
content: ["./dist/*.html"],
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
};
this is postcss.config.js
const tailwindcss = require("tailwindcss");
module.exports = {
plugins: ["postcss-preset-env", tailwindcss],
};
this is webpack.config.js
module.exports = {
mode: "development",
target: "web",
entry: ["regenerator-runtime/runtime", "./src/index.js"],
output: {
filename: "bundle.js",
path: path.join(__dirname, "dist"),
publicPath: "/",
},
resolve: {
extensions: [".js", ".css"],
alias: {
components: path.resolve(__dirname, "src/components"),
},
},
devtool: "eval",
module: {
rules: [
{ test: /\.(js|jsx)/, loader: "babel-loader", exclude: /node_modules/ },
{ test: /\.css$/, use: ["style-loader", "css-loader", "postcss-loader"] },
{
test: /\.(woff(2)?|ttf|eot|jpg|jpeg|png|gif)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].[contenthash].[ext]",
outputPath: "fonts/",
}, }, ], },
],
},
devServer: {
static: {
directory: path.resolve(__dirname, "dist"),
},
historyApiFallback: true,
},
plugins: [ ],
};
this is index.css
#tailwind base;
#tailwind components;
#tailwind utilities;
// for testing to see if this page is loading. color is set correctly
body {
color: green;
}
tailwind is still not loading
the issue was with the tailwind.config.js. It should be like this
/** #type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
theme: {
extend: {},
},
plugins: [],
};

PostCSS with .css file not rendering the nested classes nor pseudo classes

tw-imports.css
#tailwind base;
#tailwind components;
#tailwind utilities;
tailwind.config.js
const { createGlobPatternsForDependencies } = require('#nrwl/angular/tailwind');
const { join } = require('path');
module.exports = {
mode: 'jit',
content: [
join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html}'),
...createGlobPatternsForDependencies(__dirname),
],
darkMode: 'media',
theme: {
extend: {},
},
plugins: [],
};
postcsss.config.js
module.exports = {
plugins: [
'postcss-import',
'tailwindcss',
'postcss-flexbugs-fixes',
'postcss-nested',
'postcss-custom-properties',
'autoprefixer',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
features: {
'custom-properties': true,
'nesting-rules': true,
},
},
],
],
}
css
.button {
#apply rounded text-slate-500 ring-slate-900/5 shadow p-3 ring-2;
&:hover {
--mainColor: #b3a5c0;
color: var(--mainColor);
}
}
.storybook/main.js
module.exports = {
stories: [],
addons: [
'#storybook/addon-essentials',
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
}
}
}
],
core: {
builder: 'webpack5',
},
// uncomment the property below if you want to apply some webpack config globally
webpackFinal: async (config, { configType }) => {
// Make whatever fine-grained changes you need that should apply to all storybook configs
// Return the altered config
return config;
},
};
result
Here is a postcss.config.js example from my most recent project. I am using tailwindcss/nesting which still wraps postcss-nested as explained here https://tailwindcss.com/docs/using-with-preprocessors#nesting
module.exports = {
plugins: {
"postcss-import": {},
"tailwindcss/nesting": {},
tailwindcss: {},
autoprefixer: {},
cssnano: {
preset: "default",
autoprefixer: { add: false },
},
},
}
I had a similar problem as you a while back, and package versions were important, so here is my package.json.
"devDependencies": {
"#tailwindcss/line-clamp": "^0.4.0",
"#tailwindcss/typography": "^0.5.2",
"autoprefixer": "^10.2.5",
"cssnano": "^4.1.11",
"postcss": "^8.4.14",
"postcss-cli": "^9.1.0",
"postcss-custom-media": "^7.0.8",
"postcss-import": "^14.1.0",
"postcss-nested": "^5.0.5",
"postcss-preset-env": "^6.7.0",
"tailwindcss": "^3.1.2"
}
This is TailwindCSS v3, and it looks like you may be using v2, but hopefully it is still useful.

[PURGECSS]: Webpack 5 + VueJS + CSS modules stripping all classes from CSS bundle using PURGECSS

When using CSS modules with VueJS and Webpack 5, all classes are removed from the CSS bundle.
In the options for css-loader, if I have modules: true the CSS bundle is totally empty.
If I comment that out, the CSS bundle is as expected with all unused classes removed, however the JS bundle no longer has the CSS classes on the component elements.
If I add the SCSS files to the entry and do not use CSS modules, the CSS bundle is correct as well.
The issue appears to be when combining modules: true and purgecss.
Version:
"webpack": "^5.26.1"
"postcss-loader": "^5.2.0"
"postcss-preset-env": "^6.7.1"
Here is my Webpack config:
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.config');
const MiniCSSExtractPlugin = require('mini-css-extract-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const path = require('path')
const glob = require("glob");
const prodConfig = {
mode: 'production',
module: {
rules: [
{
test: /\.scss$/,
use: [
{
loader: MiniCSSExtractPlugin.loader,
},
{
loader: 'css-loader',
options: { modules: true },
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
"postcss-flexbugs-fixes",
"autoprefixer",
"postcss-preset-env",
[
"#fullhuman/postcss-purgecss",
{
content: [
path.join(__dirname, "./public/index.html"),
...glob.sync(
`${path.join(__dirname, "src")}/**/*.vue`,
{
nodir: true,
}
),
],
},
],
],
},
}
},
'sass-loader',
],
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader',
'postcss-loader',
'sass-loader',
],
},
],
},
plugins: [
new MiniCSSExtractPlugin({
filename: 'style.[fullhash].css',
}),
],
};
if (process.env.BUNDLE_ANALYZER) {
prodConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = merge(commonConfig, prodConfig);

Node modules don't apply css

I'm new to React development and I try to use webpack to set up my project. Unfortunately, I have a problem with my configuration: with it, components from node_modules don't apply styles no matter if I try to build the application or to start it with webpack-dev-server.
My webpack.config.js:
const path = require('path')
const HtmlPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.jsx',
output: {
filename: 'main.js',
path: path.join(__dirname, 'dist')
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new HtmlPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.jsx?/i,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/i,
use: 'css-loader'
},
{
test: /\.(png|jpe?g|ttf|svg)/i,
use: 'file-loader'
},
]
},
devServer: {
port: 9000,
contentBase: path.join(__dirname, 'dist')
}
}
.babelrc:
{
"presets": ["#babel/preset-react"]
}
UPD: I didn't mean the styles I wrote, but the styles of the components themselves. For example, Button component of the primereact renders like the default html button.

Combining tailwind css with sass using webpack

I'm struggling a bit getting Tailwind CSS to work with SASS and Webpack. It seems like the postcss configuration for tailwind doesn't really do anything in terms of processing #tailwind preflight, #tailwind components and #tailwind utilities
My set up is as follows:
layout.scss
#import "~tailwindcss/preflight.css";
#import "~tailwindcss/components.css";
.my-class {
#apply text-blue;
#apply border-red;
}
#import "~tailwindcss/utilities.css";
entry.js
import '../css/src/layout.scss';
postcss.config.js
const tailwindcss = require('tailwindcss');
const purgecss = require('#fullhuman/postcss-purgecss');
const cssnano = require('cssnano');
const autoprefixer = require('autoprefixer');
module.exports = {
plugins: [
tailwindcss('./tailwind.js'),
cssnano({
preset: 'default',
}),
purgecss({
content: ['./views/**/*.cshtml']
}),
autoprefixer
]
}
webpack.config.js
// NPM plugins
const autoprefixer = require('autoprefixer');
const WebpackNotifierPlugin = require('webpack-notifier');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: {
main: './scripts/entry.js'
},
output: {
filename: '[name].bundle.js',
publicPath: './'
},
watch: false,
externals: {
jquery: 'jQuery'
},
mode: 'development',
plugins: [
// Notify when build succeeds
new WebpackNotifierPlugin({ alwaysNotify: true }),
// Extract any CSS from any javascript file to process it as LESS/SASS using a loader
new MiniCssExtractPlugin({
fileame: "[name].bundle.css"
}),
// Minify CSS assets
new OptimizeCSSAssetsPlugin({}),
// Use BrowserSync plugin for file changes. I.e. if a CSS/SASS/LESS file changes, the changes will be injected directly in the browser with no page load
new BrowserSyncPlugin({
proxy: 'mysite.local',
open: 'external',
host: 'mysite.local',
port: 3000,
files: ['./dist/main.css', './views', './tailwind.js']
},
{
// disable reload from the webpack plugin since browser-sync will handle CSS injections and JS reloads
reload: false
})
],
module: {
rules: [
{
// Transpile ES6 scripts for browser support
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
use: [
{
loader: 'file-loader'
}
]
},
{
// Extract any SCSS content and minimize
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()]
}
},
{
loader: 'sass-loader',
options: {
plugins: () => [autoprefixer()]
}
}
]
},
{
// Extract any CSS content and minimize
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{ loader: 'postcss-loader' }
]
}
]
}
};
When I run Webpack, everything runs just fine, but the content of /dist/main.css is:
#tailwind preflight;#tailwind components;#tailwind utilities;.my-class{#apply text-blue;#apply border-red}
I suspect it's related to the (order of) loaders, but I can't seem to figure out why it's not getting processed correctly.
Does anyone know what I'm doing wrong here? :-)
Thanks in advance.
Wow, so after fiddling around with the loaders even more, I made it work :-) For future reference:
I added options: { importLoaders: 1 } to the css-loader for SCSS files and removed: plugins: () => [autoprefixer()] from the postcss-loader in my webpack.config.js file.
Full, updated webpack.config.js file:
// NPM plugins
const autoprefixer = require('autoprefixer');
const WebpackNotifierPlugin = require('webpack-notifier');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: {
main: './scripts/entry.js'
},
output: {
filename: '[name].bundle.js',
publicPath: './'
},
watch: false,
externals: {
jquery: 'jQuery'
},
mode: 'development',
plugins: [
// Notify when build succeeds
new WebpackNotifierPlugin({ alwaysNotify: true }),
// Extract any CSS from any javascript file to process it as LESS/SASS using a loader
new MiniCssExtractPlugin({
fileame: "[name].bundle.css"
}),
// Minify CSS assets
new OptimizeCSSAssetsPlugin({}),
// Use BrowserSync plugin for file changes. I.e. if a CSS/SASS/LESS file changes, the changes will be injected directly in the browser with no page load
new BrowserSyncPlugin({
proxy: 'mysite.local',
open: 'external',
host: 'mysite.local',
port: 3000,
files: ['./dist/main.css', './views', './tailwind.js']
},
{
// disable reload from the webpack plugin since browser-sync will handle CSS injections and JS reloads
reload: false
})
],
module: {
rules: [
{
// Transpile ES6 scripts for browser support
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
use: [
{
loader: 'file-loader'
}
]
},
{
// Extract any SCSS content and minimize
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader',
options: {
plugins: () => [autoprefixer()]
}
}
]
},
{
// Extract any CSS content and minimize
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{ loader: 'postcss-loader' }
]
}
]
}
};
There is an extension called tailwindcss-transpiler which compiles your layout.tailwind.scss files into pure CSS files.It also optimizing features.I hope it will be useful.
For VS Code
https://marketplace.visualstudio.com/items?itemName=sudoaugustin.tailwindcss-transpiler
For Atom
https://atom.io/packages/tailwindcss-transpiler

Resources