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

CSS Modules doesn't get inserted in the build output #73

Closed
xeho91 opened this issue Mar 24, 2022 · 11 comments
Closed

CSS Modules doesn't get inserted in the build output #73

xeho91 opened this issue Mar 24, 2022 · 11 comments
Labels
bug Something isn't working needs reproduction Can't be reproduced

Comments

@xeho91
Copy link

xeho91 commented Mar 24, 2022

Problem description

CSS modules don't get inserted in the final build output (with ladle build).


Reproduction code

https://stackblitz.com/edit/ladle-nmhbpc

Short instructions and observations

  1. ✅ Using npm run dev (ladle serve), you can see the code working as excepted.
    Tested with *.css and *.scss file extension.

  2. ❌ Using npm run build & npm run serve, the CSS modules don't work.
    The output file ./build/assets/basic.stories.<hash_id>.css aren't being included at all, anywhere. I was excepting to see it being included in the <head> tag.
    On the other hand, the JS module ./build/assets/basic.stories.<hash_id>.js do have correct generated CSS module assigned to the components property className.

@tajo tajo added bug Something isn't working duplicate This issue or pull request already exists labels Mar 29, 2022
@tajo
Copy link
Owner

tajo commented Mar 29, 2022

Strangely, I can't reproduce this locally, only on StackBlitz. Vite does add additional <style> tags dynamically with JS at the end of <head>.

@tajo
Copy link
Owner

tajo commented Mar 29, 2022

Also, there is already an e2e test for this that runs both dev and prod modes: https://github.com/tajo/ladle/tree/master/tests/css

@xeho91
Copy link
Author

xeho91 commented Apr 1, 2022

I've cloned your repo locally, and the tests does fail in the production - script test-pod in ./tests/css:

There's the output
> test-css@0.0.9 test-prod /home/xeho91/Projects/ladle/tests/css
> start-server-and-test serve-prod 61000 'PW_EXPERIMENTAL_TS_ESM=1 npx playwright test'

1: starting server using command "npm run serve-prod"
and when url "[ 'http://localhost:61000' ]" is responding with HTTP status code 200
running tests using command "PW_EXPERIMENTAL_TS_ESM=1 npx playwright test"


> test-css@0.0.9 serve-prod
> http-server build -c-1 -s -p 61000

(node:84553) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:84592) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)

Running 1 test using 1 worker

  ✘  tests/hello.spec.ts:3:1 › css, css modules and postcss are loaded correctly (10s)


  1) tests/hello.spec.ts:3:1 › css, css modules and postcss are loaded correctly ===================

    Error: expect(received).toHaveCSS(expected)

    Expected string: "rgb(255, 0, 0)"
    Received string: "rgb(0, 0, 0)"
    Call log:
      - expect.toHaveCSS with timeout 5000ms
      - waiting for selector "h2"
      -   selector resolved to <h2 class="_red_1822u_1">Red</h2>
      -   unexpected value "rgb(0, 0, 0)"
      -   selector resolved to <h2 class="_red_1822u_1">Red</h2>
      -   unexpected value "rgb(0, 0, 0)"
      -   selector resolved to <h2 class="_red_1822u_1">Red</h2>
      -   unexpected value "rgb(0, 0, 0)"
      -   selector resolved to <h2 class="_red_1822u_1">Red</h2>
      -   unexpected value "rgb(0, 0, 0)"
      -   selector resolved to <h2 class="_red_1822u_1">Red</h2>
      -   unexpected value "rgb(0, 0, 0)"
      -   selector resolved to <h2 class="_red_1822u_1">Red</h2>
      -   unexpected value "rgb(0, 0, 0)"
      -   selector resolved to <h2 class="_red_1822u_1">Red</h2>
      -   unexpected value "rgb(0, 0, 0)"
      -   selector resolved to <h2 class="_red_1822u_1">Red</h2>
      -   unexpected value "rgb(0, 0, 0)"


       7 |     "rgb(255, 255, 0)",
       8 |   );
    >  9 |   await expect(page.locator("h2")).toHaveCSS("color", "rgb(255, 0, 0)");
         |                                    ^
      10 |   await expect(page.locator("h3")).toHaveCSS("font-size", "36px");
      11 | });
      12 |

        at /home/xeho91/Projects/ladle/tests/css/tests/hello.spec.ts:9:36


  1 failed
    tests/hello.spec.ts:3:1 › css, css modules and postcss are loaded correctly ====================
Error: Command failed with exit code 1: PW_EXPERIMENTAL_TS_ESM=1 npx playwright test
    at makeError (/home/xeho91/Projects/ladle/tests/css/node_modules/.pnpm/execa@5.1.1/node_modules/execa/lib/error.js:60:11)
    at handlePromise (/home/xeho91/Projects/ladle/tests/css/node_modules/.pnpm/execa@5.1.1/node_modules/execa/index.js:118:26)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  shortMessage: 'Command failed with exit code 1: PW_EXPERIMENTAL_TS_ESM=1 npx playwright test',
  command: 'PW_EXPERIMENTAL_TS_ESM=1 npx playwright test',
  escapedCommand: '"PW_EXPERIMENTAL_TS_ESM=1 npx playwright test"',
  exitCode: 1,
  signal: undefined,
  signalDescription: undefined,
  stdout: undefined,
  stderr: undefined,
  failed: true,
  timedOut: false,
  isCanceled: false,
  killed: false
}
 ELIFECYCLE  Command failed with exit code 1.

@xeho91
Copy link
Author

xeho91 commented Apr 1, 2022

The only difference is that I use pnpm instead of npm; I am unsure if this matters.

P.S. I'd be happy to help investigate this issue more. However, I need help finding a part responsible for loading CSS modules in the codebase.

@jkempff
Copy link

jkempff commented Apr 11, 2022

I ran into the same issue (MyCSSModule.123.css not being included in prod build) and also tried to run the tests from ./test/css. I've had a weird finding there: It looks like it makes a different, if you use yarn or npm:

This fails for me:

rm -rf node_modules
npm install
npm run build
npm run test-prod

While this does not fail:

rm -rf node_modules
yarn install
yarn run build
yarn run test-prod

Looks like npm install (not recognizing yarn.lock) resolves in a slightly different dependency tree, which then produces a different build. 🤯
Maybe you can confirm this @xeho91 ?

@waspeer
Copy link

waspeer commented Apr 13, 2022

I'm having the same issue. Reinstalling with yarn did not work for me either. The styles work fine in dev mode, but after build they are not included. Classnames are set correctly though.

@Gomah
Copy link

Gomah commented Apr 21, 2022

Having the same issue here... Tried to dig deeper into ladle's dependencies but weirdly, I have inconsistent results, sometimes it inject the CSS, sometimes it doesn't 🤷🏻

Here's a quick & dirty fix if anyone's interested:

// inject-css.js
const fs = require('fs');
const path = require('path');
const { parse } = require('node-html-parser');
const fg = require('fast-glob');

function getCssFilesPath() {
  return fg.sync(['./build/assets/**.css']).map((filePath) => filePath.replace(/^.\/build/gi, ''));
}

async function appendCssToHtml(html) {
  const root = parse(html);

  const cssPaths = getCssFilesPath();
  const documentHead = root.querySelector('head');

  if (documentHead) {
    const links = [];
    for (let index = 0; index < cssPaths.length; index += 1) {
      const cssPath = cssPaths[index];

      links.push(`<link rel="stylesheet" href="${cssPath}" />`);
    }

    // For some reason appendChild doesn't work, using the `set_content` API from `node-html-parser` instead:
    documentHead.set_content(
      `${documentHead.toString().replace(/\<\/head\>|\<head\>/, '')}
      ${links.toString().replace(/,/g, '')}`
    );
  }

  // Replace index.html with the new css files
  fs.writeFileSync(path.join(__dirname, './build/index.html'), root.toString());
}

const ladleHtmlFile = fs.readFileSync(path.join(__dirname, './build/index.html'), 'utf8');

appendCssToHtml(ladleHtmlFile);
{
  "scripts": {
    "dev": "ladle serve --open=none",
    "build": "ladle build && yarn build:inject-css",
    "build:inject-css": "node inject-css.js"
  },
}

@tajo
Copy link
Owner

tajo commented May 18, 2022

I am trying to reproduce this locally and remotely (stackblitz) with v0.15.1 using npm, yarn, pnpm... no luck. Can anyone else verify it's still happening with the latest version? There were some significant vite updates since then so it might got fixed? If not, I'll close this in a week.

@tajo tajo added needs reproduction Can't be reproduced and removed duplicate This issue or pull request already exists labels May 18, 2022
@Gomah
Copy link

Gomah commented May 18, 2022

@tajo Can confirm it works for me now with vite 2.9.9 & ladle 0.15.1.

@waspeer
Copy link

waspeer commented May 18, 2022

Same! Using ladle 0.15.1

@tajo
Copy link
Owner

tajo commented May 19, 2022

Great. Closing this.

@tajo tajo closed this as completed May 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs reproduction Can't be reproduced
Projects
None yet
Development

No branches or pull requests

5 participants