postcss/postcss-import

Supporting package.json exports paths

equinusocio opened this issue ยท 4 comments

Hi, I would like to ask if is it possible to make postcss-import consider the exports paths defined in package.json too. For example, the following exports are working in node/js where the paths/alias are resolved correctly.

"exports": {
    ".": "./dist/themes.css",
    "./dark.css": "./dist/themes/dark.css",
    "./light.css": "./dist/themes/light.css"
}

But unfortunately, they work only if the import is from inside a js file, so importing PACKAGE/dark.css the file is resolved correctly to PACKAGE/dist/themes/dark.css (dist is inside the shipped package).

If the import is from a CSS file parsed by PostCSS, postcss-import doesn't find the file since the export/alias is ignored, to make it work inside CSS, the real path must be used:

/* This works in both JS and CSS, */
@import "PACKAGE/dist/themes/dark.css"
/* This works only in JS but not CSS */
import "PACKAGE/dark.css"

This makes us do weird stuff by moving files outside dist and delete, to avoid the dist segment in the import path.

Is this something possible?

We use https://github.com/browserify/resolve for our module resolution, which doesn't support exports, so it's not possible at present; when resolve adds support for it, we'll probably do the same. Closing this out for now, can track progress there at browserify/resolve#222.

@equinusocio We ran into this exact issue this week, and worked around it by setting postcss-import's resolve option to a function that leverages Node's in-built require.resolve() method. (Bearing in mind, we're working within the confines of our own component library, so can be assured all modules we're @importing are first-party and properly define their own exports).

// postcss.config.js
module.exports = {
  plugins: [
    require('postcss-import')({
      resolve(id) {
        return require.resolve(id);
      },
    }),
  ],
};

@RyanZim Is this a massive over-simplification of the underlying shortcoming with browserify's module resolution when it comes to the exports field?

@adamduncan Your solution works; the only problem is that it only works with exports; it doesn't add .css extensions, or respect the style field in package.json, so we can't implement it here for everyone.

Thanks @RyanZim, makes sense. Have edited my original comment to include the caveat re: exclusively relying on exports in our use-case. Hope that helps to clarify for others.