Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@apply can not be used (with postcss-import and webpack) #449

Closed
regnerisch opened this issue Apr 9, 2018 · 16 comments
Closed

@apply can not be used (with postcss-import and webpack) #449

regnerisch opened this issue Apr 9, 2018 · 16 comments

Comments

@regnerisch
Copy link

This may be the better place (duplicate of tailwindlabs/webpack-starter#12)

I have this error:

    ERROR in ./assets/main/components/components-critical.css (./node_modules/css-loader??ref--4-2!./node_modules/postcss-loader/lib!./assets/main/components/components-critical.css)
    Module build failed: Syntax Error 
    
    (2:5) `@apply` cannot be used with `.w-full` because `.w-full` either cannot be found, or it's actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that `.w-full` exists, make sure that any `@import` statements are being properly processed *before* Tailwind CSS sees your CSS, as `@apply` can only be used for classes in the same CSS tree.
    
      1 | .nav {
    > 2 |     @apply .w-full;
        |     ^
      3 | }
      4 | 

And I do not know where this problem occures

My webpack.config:

const path = require('path');
const ManifestPlugin = require('webpack-manifest-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = function (env, argv) {
  return {
    entry: {
      'main-base': [
        './assets/main/base/index.css',
      ],
      'main-components-critical': [
        './assets/main/components/index-critical.js',
      ],
      'main-components': [
        './assets/main/components/index.js',
      ],
      'react': [
        './assets/main/components/react.js',
      ],
      'main-utilities': [
        './assets/main/utilities/index.css',
      ],
    },
    output: {
      path: path.resolve(__dirname, 'web/public/assets'),
      filename: '[name].[hash].js',
      chunkFilename: '[name].[hash].js'
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'style-loader',
            MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                importLoaders: 1,
                minimize: argv['mode'] === 'production'
              }
            },
            'postcss-loader'
          ]
        },
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: ['babel-loader']
        }
      ]
    },
    plugins: [
      new ManifestPlugin(),
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: '[name].[hash].css',
        chunkFilename: '[name].[hash].css'
      })
    ]
  }
};

Tailwind preflight is in assets/main/base/index.css (@import 'tailwindcss/preflight';)
Tailwind utilities is in assets/main/utilities/index.css (@import 'tailwindcss/utilities';)

And in assets/main/components/navigation/style-critical.css I have the @apply this stylesheet is imported in assets/main/components/components-critical.css (@import './navigation/style-critical.css';)

I think everything is configured as expected from tailwind
postcss.config.js

module.exports = {
  plugins: [
    require('postcss-import'),
    require('tailwindcss')('./tailwind.js'),
    require('postcss-cssnext'),
    require('postcss-flexbugs-fixes')
  ]
};

and package.json

  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.11",
    "install": "^0.10.4",
    "mini-css-extract-plugin": "^0.4.0",
    "postcss-cssnext": "^3.1.0",
    "postcss-flexbugs-fixes": "^3.3.0",
    "postcss-import": "^11.1.0",
    "postcss-loader": "^2.1.3",
    "react": "^16.3.1",
    "react-dom": "^16.3.1",
    "react-router-dom": "^4.2.2",
    "rimraf": "^2.6.2",
    "style-loader": "^0.20.3",
    "tailwindcss": "^0.5.2",
    "webpack": "^4.5.0",
    "webpack-cli": "^2.0.14",
    "webpack-manifest-plugin": "^2.0.0-rc.2"
  },

If you need more information let me know. I do not know what I am doing wrong :(

@adamwathan
Copy link
Member

adamwathan commented Apr 10, 2018

Can you publish a repository that reproduces this so I can clone it and troubleshoot? I'm guessing it's related to the critical CSS stuff; Tailwind can only @apply classes that it can see in the same tree, so if the critical CSS stuff is processed separately, @apply won't work because Tailwind won't be able to find any of the classes.

@tanc
Copy link

tanc commented Apr 11, 2018

I'm having the same problem. If I add @tailwind utilities in the sass partial which has the @apply directive then it compiles fine but I get duplicate utilities printed in the output. Otherwise I see the failure message like:

`@apply` cannot be used with...

@tanc
Copy link

tanc commented Apr 11, 2018

My repo is: https://github.com/tanc/particle-playground
To get set up:

npm install
npm run setup

Then run npm start and you should see the errors.

@regnerisch
Copy link
Author

Here is mine:

https://github.com/Tera3yte/tailwind-apply-error

npm i & npm run build

@adamwathan
Copy link
Member

@Tera3yte So in your case it's like I mentioned in my earlier comment, the Tailwind styles don't exist in your critical CSS tree so they can't be applied. I'd like to make it possible to apply Tailwind classes even if they don't exist eventually but right now it's not supported; it's going to be quite complex to implement.

The way @apply works is by looking for that class in the current CSS tree, so since ./assets/main/components/index-critical.js is processed independently and doesn't contain any of the Tailwind classes, Tailwind won't be able to find them for you to apply them.

@adamwathan
Copy link
Member

@tanc Not sure what's going on with yours, I can't get it to run locally and the errors I'm seeing are not Tailwind related:

> [email protected] dev:pl /Users/adamwathan/Code/particle-playground
> npm-run-all --continue-on-error --parallel dev:pl:gulp dev:pl:webpack


> [email protected] dev:pl:gulp /Users/adamwathan/Code/particle-playground
> NODE_ENV='development' gulp compile


> [email protected] dev:pl:webpack /Users/adamwathan/Code/particle-playground
> webpack-dev-server --config ./apps/pl/webpack.pl.dev.js --hot

[11:30:27] Using gulpfile ~/Code/particle-playground/gulpfile.js
[11:30:27] Starting 'compile'...
[11:30:27] Starting 'compile:pl:env'...
[11:30:27] Finished 'compile:pl:env' after 8.18 ms
[11:30:27] Starting 'compile:twig-namespaces'...
[11:30:27] Finished 'compile:twig-namespaces' after 104 ms
[11:30:27] Starting 'compile:pl'...
configuring pattern lab...

Notice: Undefined index: primary in /Users/adamwathan/Code/particle-playground/apps/pl/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 77
your site has been generated...
site generation took 0.45531296730042 seconds and used 24MB of memory...

[11:30:28] Finished 'compile:pl' after 526 ms
[11:30:28] Starting 'compile:pl:notify'...
[11:30:28] Finished 'compile:pl:notify' after 536 μs
[11:30:28] Finished 'compile' after 640 ms
(node:54307) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
    at Child.Base.apply (/Users/adamwathan/Code/particle-playground/node_modules/run-plugin-webpack/index.js:141:11)
    at webpack (/Users/adamwathan/Code/particle-playground/node_modules/webpack/lib/webpack.js:37:12)
    at startDevServer (/Users/adamwathan/Code/particle-playground/node_modules/webpack-dev-server/bin/webpack-dev-server.js:379:16)
    at processOptions (/Users/adamwathan/Code/particle-playground/node_modules/webpack-dev-server/bin/webpack-dev-server.js:361:5)
    at Object.<anonymous> (/Users/adamwathan/Code/particle-playground/node_modules/webpack-dev-server/bin/webpack-dev-server.js:504:1)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)
events.js:165
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE 0.0.0.0:8080
    at Server.setupListenHandle [as _listen2] (net.js:1346:14)
    at listenInCluster (net.js:1387:12)
    at doListen (net.js:1502:7)
    at process._tickCallback (internal/process/next_tick.js:178:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:697:11)
    at startup (internal/bootstrap/node.js:201:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)
Emitted 'error' event at:
    at emitErrorNT (net.js:1366:8)
    at process._tickCallback (internal/process/next_tick.js:178:19)
    [... lines matching original stack trace ...]
    at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] dev:pl:webpack: `webpack-dev-server --config ./apps/pl/webpack.pl.dev.js --hot`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] dev:pl:webpack script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/adamwathan/.npm/_logs/2018-04-11T15_30_29_070Z-debug.log
ERROR: "dev:pl:webpack" exited with 1.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] dev:pl: `npm-run-all --continue-on-error --parallel dev:pl:gulp dev:pl:webpack`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] dev:pl script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/adamwathan/.npm/_logs/2018-04-11T15_30_29_101Z-debug.log
error An unexpected error occurred: "Command failed.
Exit code: 1
Command: sh
Arguments: -c npm run dev:pl
Directory: /Users/adamwathan/Code/particle-playground
Output:
".
info If you think this is a bug, please open a bug report with the information provided in "/Users/adamwathan/Code/particle-playground/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I suspect it's a similar problem; the Tailwind classes don't actually exist in whatever CSS tree is being processed. Do you have multiple SCSS entry points in that project, or is it a single base SCSS file that imports everything else?

@tanc
Copy link

tanc commented Apr 11, 2018

Looks like you might have a port clash on 8080 Error: listen EADDRINUSE 0.0.0.0:8080

But I think you're right there are multiple entry points, each component has an entry point and associated scss file. There is a base scss file which imports two of the tailwind includes but all the other project scss files are included with webpack through an index.js per component.

So there is no way to include the tailwind utilities with each component and not have them duplicated in the final output?

@adamwathan
Copy link
Member

So there is no way to include the tailwind utilities with each component and not have them duplicated in the final output?

Not currently no, Tailwind can only @apply classes it can see. I'm planning to make it possible to @apply classes that don't exist in the CSS but would be generated by Tailwind if you did add @tailwind utilities to that file eventually; likely late May or early June when I've got some time to focus on Tailwind again.

@tanc
Copy link

tanc commented Apr 11, 2018

No problem, thanks for the hard work on Tailwind, it looks very promising

@tanc
Copy link

tanc commented Apr 11, 2018

I found a workaround: add @tailwind utilities to any file that needs it for @apply purposes, then in the webpack pipeline use Optimize CSS Assets Webpack Plugin which will dedupe the output. Not the most elegant solution but it seems to work.

@LeBenLeBen
Copy link

LeBenLeBen commented Nov 2, 2019

In case anyone stumble upon this issue… I had a similar issue where @apply wouldn't be parsed by tailwind. I was able to make it work by loading Tailwind plugin after postcss-import in my postcss.config.js, like this:

module.exports = {
  plugins: {
    'postcss-import': {},
    tailwindcss: {},
  },
};

Edit: This is actually perfectly well explained in the docs 😬

@mfodor
Copy link

mfodor commented Jun 2, 2020

DO NOT write dot. Only the class name.

// use
@apply css-class;

// instead of
@apply .css-class;

@ItalyPaleAle
Copy link

I'm having the same issue and looks like it's caused by enabling importLoaders: 1 in the options for css-loader, which causes a conflict with postcss-import.

However… without importLoader I can't load a Fork-Awesome, getting an error that it can't resolve ../fonts

@mrt-web-old
Copy link

mrt-web-old commented Dec 15, 2020

I used an other technique as an alternative using vuejs:

   `
	data() {
		return {
			_: {
				btn: "inline-flex items-center justify-center px-5 py-3 border border-transparent focus:outline-none focus:shadow-outline text-base leading-6 font-medium rounded-md transition duration-150 ease-in-out",
				"btn-primary": "text-white bg-indigo-600 hover:bg-indigo-500",
				"btn-secondary": "text-indigo-600 bg-white hover:text-indigo-500",
				get: (classes) => classes.split(' ').map(e=> this._[e]).join(' '),

			},
		};
	},

`

usage:
<a href="#" :class="_.get('btn btn-secondary')">Learn more</a>

@codehunter12345
Copy link

For me, It was a mistake putting my custom class name inside @apply {} section:

.myclass{
}

.table-header {
  @apply text-lg  font-bold myclass;
}

@oussematn
Copy link

make sure you install 'postcss-import'

then, in tailwind.config.js:
plugins: [ require('postcss-import'), require('tailwindcss'), require('autoprefixer') ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants