Export Multiple Stylesheets to postcss-import


Here's how to export multiple stylesheets to postcss-import.

postcss-import is a postcss plugin that allows you to import other CSS files into your CSS stylesheet.

Node.js has named imports, and there's magic to them. There's magic here too, but it's next-level, because Node packages were designed to wrap JS files. This is CSS. So there are two fields on package.json that point to the actual CSS file in the package. One, main, is standard, and used by JS as well. style is a non-standard field that the library uses. So package.json can look like:

"main": "src/components.css",
"style": "src/components.css",

Node has a more recent method of exporting multiple paths with conditional exports, but postcss-import doesn't support it, because it uses browserify.resolve under the hood, and it doesn't support it yet. If it did, we get this nice thing that doesn't currently work in package.json:

"exports": {
  "./base.css": {
    "import": "./src/base.css",
    "require": "./src/base.css"
  },
  "./components.css": {
    "import": "./src/components.css",
    "require": "./src/components.css"
  }
},

Without conditional exports, what can we do for our stylesheets? We can use another feature of postcss-import that looks for files in certain paths. We will give it the package node_modules path, and name matches on that path will be inlined in the stylesheet.

When we set up our postcss-import plugin in postcss.config.js, we'll set the path field:

module.exports = {
  plugins: {
    'postcss-import': {
      path: ['node_modules/@angel/photon/src'],
    },
    '@tailwindcss/nesting': {},
    tailwindcss: {},
    autoprefixer: {},
  },
}

And in our package, instead of having a generically-named base.css and components.css file, we should be a namespacing prefix on the file name to make it package-specific. Then we can import like this:

@import 'photon-base.css';
@import 'photon-components.css';

Did it work for you? Are there better solutions? (Hopefully someday.)