sveltejs / svelte-preprocess

A ✨ magical ✨ Svelte preprocessor with sensible defaults and support for: PostCSS, SCSS, Less, Stylus, Coffeescript, TypeScript, Pug and much more.
MIT License
1.72k stars 147 forks source link

PostCSS configuration was not passed or is invalid #470

Open wiesson opened 2 years ago

wiesson commented 2 years ago

Describe the bug I have an issue when I'd like to use the tailwind @apply syntax within a Svelte template:

<style>
.my-button {
  @apply bg-gray-50
}
</style>

It works without any issue in a new project npm init svelte@next svelte-next but not in our existing project. Whats interesting, if I change something in a file it sometimes reloads and it just works as expected.

Logs

[svelte-preprocess] PostCSS configuration was not passed or is invalid. If you expect to load it from a file make sure to install "postcss-load-config" and try again. Error: Cannot find module '/Users/wiese/Dev/project/project-web/package.json' imported from '/Users/wiese/Dev/project/project-web/node_modules/.pnpm/lilconfig@2.0.4/node_modules/lilconfig/dist/index.js'

and/or:


/Users/wiese/Dev/project/project-web/src/components/auth/LoginOverlay.svelte:7:131 Semicolon or block is expected
  5 |  
  6 |  .input {
  7 |    @apply appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-gray-500 focus:border-gray-500 focus:z-10 sm:text-sm;
                                                                                                                                          ^
  8 |  }
  9 |  

Expected behavior I'd like to understand why it happens and how I could find the issue because it works in a new project.

Information about your project:

svelte.config.js ```javascript import adapter from "@sveltejs/adapter-vercel"; import preprocess from "svelte-preprocess"; import { resolve } from "path"; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: [preprocess({ postcss: true })], kit: { adapter: adapter(), target: "#svelte", vite: { ssr: { noExternal: ["svelte-hero-icons"], }, resolve: { alias: { $components: resolve("src/components"), $icons: resolve("src/components/icons"), }, }, }, }, }; export default config; ```
postcss.config.cjs ```Javascript const tailwindcss = require("tailwindcss"); const autoprefixer = require("autoprefixer"); const config = { plugins: [ tailwindcss(), autoprefixer(), ], }; module.exports = config; ```
package.json ```json { "dependencies": { "@googlemaps/js-api-loader": "^1.13.2", "@supabase/supabase-js": "^1.29.4", "@uploadcare/upload-client": "^2.2.0", "algoliasearch": "^4.12.0", "autonumeric": "^4.6.0", "clearbit": "^1.3.5", "cohere-js": "^1.0.19", "color": "^4.2.0", "datebook": "^7.0.8", "instantsearch.js": "^4.37.3", "jsonwebtoken": "^8.5.1", "libphonenumber-js": "^1.9.46", "lodash-es": "^4.17.21", "mapbox-gl": "^2.6.1", "marked": "^4.0.12", "node-fetch": "^3.2.0", "pluralize": "^8.0.0", "svelte-hero-icons": "^4.0.3", "tldjs": "^2.3.1", "ua-parser-js": "^1.0.2", "uploadcare-widget": "^3.16.0", "zxcvbn": "^4.4.2" }, "devDependencies": { "@sveltejs/adapter-vercel": "^1.0.0-next.39", "@sveltejs/kit": "^1.0.0-next.247", "@tailwindcss/aspect-ratio": "^0.4.0", "@tailwindcss/forms": "^0.4.0", "@tailwindcss/line-clamp": "^0.3.1", "@tailwindcss/typography": "^0.5.0", "@tsconfig/svelte": "^3.0.0", "@types/lodash-es": "^4.17.5", "@types/pluralize": "^0.0.29", "autoprefixer": "^10.4.2", "cssnano": "^5.0.16", "postcss": "^8.4.5", "postcss-load-config": "^3.1.1", "prettier": "^2.5.1", "prettier-plugin-svelte": "^2.6.0", "svelte": "^3.46.3", "svelte-check": "^2.3.0", "svelte-preprocess": "^4.10.2", "tailwindcss": "^3.0.17", "tslib": "^2.3.1", "typescript": "^4.5.5", "vite": "^2.7.13" }, "type": "module" } ```
f-elix commented 2 years ago

I have the same issue very inconsistently. Very hard to track down the cause.

wiesson commented 2 years ago

I have noticed that a file is being requested with ?svelte&type=style&lang.css <- lang css, but I have explicitly set it to postcss

<style lang="postcss">
.root {
  @apply inline-flex text-center justify-center items-center leading-7 h-5;
}
...
</style>

Error:

hmr update /src/components/LoadingDots.svelte?svelte&type=style&lang.css
[svelte-preprocess] PostCSS configuration was not passed or is invalid. If you expect to load it from a file make sure to install "postcss-load-config" and try again.
nodra-vr commented 2 years ago

I'm running into a similar issue, but I do not use @apply in my codebase. Then again I do include DaisyUIi and TailwindCSS, both of those have @apply in them. So far I have been unable to replicate or track down the exact cause. It happens at random. and resetting cache and/or renaming the postccs.config.cjs file while reloading the dev server might fix it for a while sometimes.

I have not been able to get builds to bug out it only seems to happen on the dev server.

Information about your project:

Latest Chome and Brave Manjaro Linux (fully updated) Node, v17.3.0 preprocess: 4.10.1, sveltekit 1.0.0-next.231

Note: versions are a bit older than OP Edit: Updated to 4.10.2 && 1.0.0-next.247; same issues

error message
13:42:50 [vite] Internal server error: Cannot find module '/home/.../postcss.config.cjs' imported from '/home/.../node_modules/vite/dist/node/chunks/dep-0351185a.js'
  Plugin: vite:css
  File: /home/.../src/app.css
      at viteResolve (/home/.../node_modules/vite/dist/node/chunks/dep-0351185a.js:60123:25)
      at Function._resolveFilename (/home/.../node_modules/vite/dist/node/chunks/dep-0351185a.js:60137:20)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at Object.search (/home/...g/node_modules/vite/dist/node/chunks/dep-0351185a.js:12723:37)
      at async resolvePostcssConfig (/home/,,,/node_modules/vite/dist/node/chunks/dep-0351185a.js:20506:22)
      at async compileCSS (/home/.../node_modules/vite/dist/node/chunks/dep-0351185a.js:20329:27)
      at async TransformContext.transform (/home/.../node_modules/vite/dist/node/chunks/dep-0351185a.js:20015:50)
      at async Object.transform (/home/,,,/node_modules/vite/dist/node/chunks/dep-0351185a.js:36985:30)
package.json

{
    "name": "a-hackaton",
    "version": "0.0.1",
    "scripts": {
        "dev": "env-cmd svelte-kit dev",
        "build": "svelte-kit build",
        "package": "svelte-kit package",
        "preview": "svelte-kit preview",
        "check": "svelte-check --tsconfig ./tsconfig.json",
        "check:watch": "svelte-check --tsconfig ./tsconfig.json --watch",
        "lint": "prettier --ignore-path .gitignore --check --plugin-search-dir=. . && eslint --ignore-path .gitignore .",
        "format": "prettier --ignore-path .gitignore --write --plugin-search-dir=. ."
    },
    "devDependencies": {
        "@noble/ed25519": "^1.5.1",
        "@noble/hashes": "^1.0.0",
        "@sveltejs/adapter-auto": "next",
        "@sveltejs/kit": "next",
        "@tailwindcss/typography": "^0.5.0",
        "@types/mongoose": "^5.11.97",
        "@typescript-eslint/eslint-plugin": "^4.31.1",
        "@typescript-eslint/parser": "^4.31.1",
        "autoprefixer": "^10.4.2",
        "buffer": "^6.0.3",
        "cookie": "^0.4.1",
        "daisyui": "^1.23.0",
        "env-cmd": "^10.1.0",
        "eslint": "^7.32.0",
        "eslint-config-prettier": "^8.3.0",
        "eslint-plugin-svelte3": "^3.2.1",
        "graphql": "^16.2.0",
        "graphql-request": "^3.7.0",
        "mongodb": "^4.3.0",
        "mongoose": "^6.1.7",
        "near-api-js": "^0.44.2",
        "postcss": "^8.4.5",
        "prettier": "^2.4.1",
        "prettier-plugin-svelte": "^2.4.0",
        "svelte": "^3.44.0",
        "svelte-check": "^2.2.6",
        "svelte-preprocess": "^4.10.1",
        "tailwindcss": "^3.0.12",
        "theme-change": "^2.0.2",
        "tslib": "^2.3.1",
        "typescript": "^4.4.3",
        "uuid": "^8.3.2"
    },
    "type": "module",
    "dependencies": {}
}
svelte.config.js
import adapter from '@sveltejs/adapter-auto';
import preprocess from 'svelte-preprocess';
import { resolve } from 'path';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    // Consult https://github.com/sveltejs/svelte-preprocess
    // for more information about preprocessors
    preprocess: [preprocess({})],

    kit: {
        adapter: adapter(),
        target: '#body',
        vite: {
            resolve: {
                alias: {
                    $schema: resolve('./src/schema'),
                },
            },
        },
    },
};

export default config;
postcss.config.cjs
const tailwindcss = require('tailwindcss');
const autoprefixer = require('autoprefixer');

const config = {
    plugins: [
        //Some plugins, like tailwindcss/nesting, need to run before Tailwind,
        tailwindcss(),
        //But others, like autoprefixer, need to run after,
        autoprefixer,
    ],
};

module.exports = config;
wiesson commented 2 years ago

Moving the postcss config to the svelte.config.js

import adapter from "@sveltejs/adapter-vercel";
import preprocess from "svelte-preprocess";
import { resolve } from "path";
import tailwindcss from "tailwindcss";
import autoprefixer from "autoprefixer";

/** @type {import('@sveltejs/kit').Config} */
const config = {
  preprocess: [
    preprocess({
      postcss: {
        plugins: [tailwindcss(), autoprefixer()],
      },
    }),
  ],
  kit: {
    adapter: adapter(),
    target: "#svelte",
    vite: {
      css: {
        postcss: {
          plugins: [tailwindcss(), autoprefixer()], // <-- here
        },
      },
      ssr: {
        noExternal: ["svelte-hero-icons"], // <-- and also here
      },
      resolve: {
        alias: {
          $components: resolve("src/components"),
          $icons: resolve("src/components/icons"),
        },
      },
    },
  },
};

export default config;

and deleting postcss.config.cjs fixed it 🤷

jycouet commented 2 years ago

@wiesson I think that you should change autoprefixer() to autoprefixer.

On my end, I could put plugin: [] in the top part (that removes duplicate).

But, I have to say that I don't really think that it's a "fix" 🤔 I would like to understand more what is going on behind.

If some people could advice? 👍

wiesson commented 2 years ago

No, it is not really a fix but at least I can continue working with that 😅 I tested both variants and only if I add the plugins to both, it works.

I'm not sure what the postcss plugin array requires. I also checked what tailwind and autoprefixer actually returns and it looks like, both are functions (tw for sure)

I would like to understand more what is going on behind.

Same here :)

f-elix commented 2 years ago

Closing my editor, terminal and browser tab seems to fix it until the next time it happens. I personally prefer that to a config change.

nodra-vr commented 2 years ago

Interesting clues, it is starting to look like the issue is that sometimes the hot reload code path does not look for the configuration file, tries to use a cached version but fails, or looks for the wrong file/setup. (resetting the hole dev env fixes it for a while, duplicating configuration into two places solves it, ...)

I can confirm that I need both configuration blocks mentioned above set to have a smooth workflow again.

hmaesta commented 2 years ago

Moving the postcss config to the svelte.config.js

Definitely not a fix, but at least a headache terminator. 🥲 (Thanks, @wiesson!)

I am facing this issue for a couple of days without any success. It just appears from nowhere. Don't know if a coincidence, but It started after I ran yarn dev --host – and, yes, I tried deleting .svelte-kit and node_modules

dummdidumm commented 2 years ago

Not sure if related, but dropping the reproduction repo here as a reminder for later which also has an issue with loading PostCSS: https://github.com/pngwn/postcss-preprocess-repro-1

chbert commented 2 years ago

Experienced the same issues for a while now as well.

robpc commented 2 years ago

Sorry, for the old thread, but I recently had this issue moving from @sveltejs/kit 1.0.0-next.328 -> 1.0.0-next.350. Updating the vite.css.plugins like @wiesson helped me as well.

eflatz commented 1 year ago

On the shoulders of @wiesson solution I had to modify svelte.config.js for svelte-kit 1.0

import preprocess from 'svelte-preprocess';
import tailwindcss from 'tailwindcss';
import autoprefixer from 'autoprefixer';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    preprocess: [
        preprocess({
            postcss: {
                plugins: [tailwindcss(), autoprefixer()]
            }
        })
    ]
};

export default config;

and vite.config.js

import { sveltekit } from '@sveltejs/kit/vite';
import { resolve } from 'path';
import tailwindcss from 'tailwindcss';
import autoprefixer from 'autoprefixer';

/** @type {import('vite').UserConfig} */
const config = {
    plugins: [sveltekit()],
    test: {
        include: ['src/**/*.{test,spec}.{js,ts}']
    },
    css: {
        postcss: {
            plugins: [tailwindcss(), autoprefixer()] // <-- here
        }
    },
    ssr: {
        noExternal: ['svelte-hero-icons'] // <-- and also here
    },
    resolve: {
        alias: {
            $components: resolve('src/components'),
            $icons: resolve('src/components/icons')
        }
    }
};

export default config;
multics commented 1 year ago
import preprocess from 'svelte-preprocess';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    preprocess: [
        preprocess({
            postcss: true // <- only this line is needed. There is no need to change vite.config.js
        })
    ]
};

export default config;
dukejones commented 1 year ago

Using the latest vitePreprocess in Sveltekit, this pops up because I'm using workspaces, and my ui package is not in the root of my repo.

"If your tailwind.config.js is not in the workspace root. Or if your project is not in the workspace root. Make sure you pass in the path to your tailwind config file in your postcss config file."

const path = require('path');
const tailwindcss = require('tailwindcss');

module.exports = {
    plugins: [tailwindcss(path.resolve(__dirname, './tailwind.config.cjs'))]
};

Source

SalvatoreVella commented 3 months ago

svelte-preprocess allows you to specify your postcss.config file path:

import adapter from "@sveltejs/adapter-vercel";
import preprocess from "svelte-preprocess";
import { resolve } from "path";

/** @type {import('@sveltejs/kit').Config} */
const config = {
        preprocess({
            postcss: {
                configFilePath: './postcss.config.cjs', // <-- your postcss.config file path
            },
        }),
...

This could be particularly useful if you want to keep a separate configuration file and resolve the [svelte-preprocess] PostCSS configuration was not passed or is invalid ... error.

ArohanD commented 1 week ago

I was running into the same issue as @dukejones, language server was unable to pick up the styles config because my repo wasn't in root. Was able to modify the vitePreProcess config as follows to place the postcss config inline and get everything working again:

// svelte.config.js
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import tailwindcss from "tailwindcss";
import autoprefixer from "autoprefixer";

/** @type {import('@sveltejs/kit').Config} */
const config = {
  preprocess: [
    vitePreprocess({
      style: {
        css: {
          postcss: {
            plugins: [tailwindcss(), autoprefixer()],
          },
        }
      }
    }),
  ],
  kit: {
    adapter: adapter(),
  },
};

export default config;