Microbundle: Inline CSS file as string - CJS bundle simply converts this to `void 0`

Created on 23 Oct 2020  路  8Comments  路  Source: developit/microbundle

Bit of a weird use case, but I need to inline a CSS file as a string within a bundle.

I can do this just fine with UMD, ES Module, and Modern outputs, but where they contain a string representation of the CSS file, the CJS output just has void 0 in its place. Bug, or is this a limitation of the CJS output in some way?

import stylesheet from "./css/styles.css";
console.log(stylesheet);

While console.log() is certainly not the "real" use case, it acts the same as the real use case and is simpler to display with.

This is also with the --css-modules flag having been set to false.

Most helpful comment

Found the bug.

All 8 comments

Strange that this would vary between CJS and the other formats.

I had thought that Microbundle's CSS handling would return a URL, not the CSS file as a string. Do you have configuration set up to alter that?

Sorry, completely forgot, using TS and therefore have a declaration file that looks like this:

declare const stylesheet: string;
export default stylesheet;

Hi @developit!

Is there a way to force importing a file content as a string?
I mean something like this:

import text from 'raw-loader!./css/styles.css'
// or
import text from './css/styles.css?as=text'

@omgovich Microbundle doesn't have loaders or anything like that. The only way to hack it in would be a Babel plugin that transforms the import inline into a string.

Thanks for the advice!

Sorry for the super long delay here, just got busy with life.

Set up a demo repo and pushed a build as well: https://github.com/rschristian/css-string-microbundle

Build outputs (prettified for easier viewing):

[_] CJS: https://github.com/rschristian/css-string-microbundle/blob/fb26f71515115127a2e7f26222f1879162322218/dist/index.js#L3
[X] Modern: https://github.com/rschristian/css-string-microbundle/blob/fb26f71515115127a2e7f26222f1879162322218/dist/index.modern.js#L5
[X] Module: https://github.com/rschristian/css-string-microbundle/blob/fb26f71515115127a2e7f26222f1879162322218/dist/index.module.js#L5
[X] UMD: https://github.com/rschristian/css-string-microbundle/blob/fb26f71515115127a2e7f26222f1879162322218/dist/index.umd.js#L5

Ideally what we're looking for is to have a string representation of the CSS file in each of the targets. In this quick demo that's just "h1{color:red}". CJS is the odd one out however and just converts what should be our string into void 0.

Ah interesting. I'm betting we are actually just failing to do CJS<->ESM default interop then and Terser is folding away the missing property access.

Found the bug.

Was this page helpful?
0 / 5 - 0 ratings