postcss-modules icon indicating copy to clipboard operation
postcss-modules copied to clipboard

Importing a value also imports (and exports) the classes defined in the imported file

Open jaap3 opened this issue 8 years ago • 4 comments

I have a simple setup with postcss-cli, postcss-imports and postcss-modules. This setup bundles a single CSS file that imports some global CSS and some CSS modules.

package.json:

{
  "devDependencies": {
    "postcss-cli": "^4.1.0",
    "postcss-import": "^10.0.0",
    "postcss-modules": "^0.8.0"
  }
}

postcss.config.js:

module.exports = {
  plugins: [
    require('postcss-import')({
      plugins: [
        require('postcss-modules')({
          globalModulePaths: ['./globals.css']
        })
      ]
    })
  ]
}

app.css:

@import url('./globals.css');
@import url('./type.css');

globals.css:

@value h1-font from './type.css';

h1 {
  font: h1-font;
}

type.css:

@value h1-font: bold 2em Helvetica, Arial, sans-serif;

.h1 {
  font: h1-font;
}

Now when I run ./node_modules/.bin/postcss app.css the output is:

.h1 {
  font: bold 2em Helvetica, Arial, sans-serif;
}
h1 {
  font: bold 2em Helvetica, Arial, sans-serif;
}
._h1_1xsib_3 {
  font: bold 2em Helvetica, Arial, sans-serif;
}

While I would expect it to be:

h1 {
  font: bold 2em Helvetica, Arial, sans-serif;
}
._h1_1xsib_3 {
  font: bold 2em Helvetica, Arial, sans-serif;
}

Is this expected behaviour? The .h1 class is not imported in globals.css so I would not expect it to be in the output.

jaap3 avatar Jun 19 '17 11:06 jaap3

Yes, this is the expected behaviour. CSS Modules don't have tree shaking and maybe they shouldn't.

madyankin avatar Jun 20 '17 03:06 madyankin

Well from my perspective this is utterly unexpected. Not only does this result in duplicate css, in this case it exposes global class names that are not supposed to be global.

I just did another test, this time using postcss-icss-import (^0.1.0):

postcss.config.js:

module.exports = {
  plugins: [
    require('postcss-icss-import'),
    require('postcss-modules')({
      globalModulePaths: ['./globals.css']
    })
  ]
}

This time the output is like what I would expect:

h1 {
  font: bold 2em Helvetica, Arial, sans-serif;
}._h1_1xsib_3 {
  font: bold 2em Helvetica, Arial, sans-serif;
}

So now I'm unsure what's correct.

jaap3 avatar Jun 20 '17 07:06 jaap3

@jaap3 Well, maybe I'm wrong. I'll play with this someday.

madyankin avatar Jun 20 '17 07:06 madyankin

postcss-icss-import is not resolved by loaders yet. It just adds

:import('path') {
  import: default;
}

Which doesn't have any references.

TrySound avatar Jun 20 '17 08:06 TrySound