indooorsman / esbuild-css-modules-plugin

A esbuild plugin to bundle css modules into js(x)/ts(x)
MIT License
91 stars 16 forks source link

CSS import statment get's added for initialOptions.bundle being true or false, when forceBuild is being used also. #70

Closed karlnorling closed 5 months ago

karlnorling commented 5 months ago

With code usage of CssModulesPlugin and esbuild:

// Adding CssModulesPlugin with force true.
plugins.push(CssModulesPlugin({
  force: true,
  emitDeclarationFile: false,
  inject: false,
  namedExports: true,
  pattern: `${packageNameVersionHash}_[hash]_[local]`,
}));
...
// Then using esbuild
esbuild.build({
    bundle: false,
    entryPoints: fileToTranspile,
    format,
    minify: false,
    outfile,
    plugins,
    target: browserslistToEsbuild(),
});

Due to the logic in: https://github.com/indooorsman/esbuild-css-modules-plugin/blob/main/lib/css.helper.js#L167-L172 It will add import "${pluginCssNamespace}:${fixImportPath(relativePath)}"; when this.build.initialOptions.bundle is true.

But also when this.build.initialOptions.bundle is false it will add the import here: https://github.com/indooorsman/esbuild-css-modules-plugin/blob/main/index.js#L205-L240 Specifically: https://github.com/indooorsman/esbuild-css-modules-plugin/blob/main/index.js#L230-L232

Request would be to add logic to https://github.com/indooorsman/esbuild-css-modules-plugin/blob/main/index.js#L230-L232 not add the import if forceBuild is true.

karlnorling commented 5 months ago

Suggested fix would be:

https://github.com/indooorsman/esbuild-css-modules-plugin/blob/main/index.js#L230-L232

contents: forceBuild ? buildResult?.js : `import './${basename(path).replace(/\.css$/i, '.built.css')}';\n${
  buildResult?.js
}`,
indooorsman commented 5 months ago

Thanks for reporting. I'll do more testings for it and come back to u asap

indooorsman commented 5 months ago

Hi @karlnorling , This behavior is by design: with bundle: false & force: true & inject: false, the import statement of built css file is needed to ensure content of css file would be kept in following build workflow.

What is your problem caused by this import statement?

karlnorling commented 5 months ago

@indooorsman Yes, I figured it was as intended. It's an issue with SSR loading of files trying to require none js files. I've worked around it by wrapping the loading / import / require of non js files in dynamic import checking window object.