ESM library generated with rollup-plugin-postcss throws Cannot find module '../node_modules/style-inject/dist/style-inject.es.js'

Viewed 724

We are maintaining an internal library which is exporting ESM modules using Rollup. We have just recently switched to using CSS modules, which we have set with rollup-plugin-postcss. We want to inject these styles into the head rather than have an external file.

Our built bundle generates the ESM file with:

import styleInject from '../node_modules/style-inject/dist/style-inject.es.js';

Our consuming library then fails with

 Uncaught Error: Cannot find module '../node_modules/style-inject/dist/style-inject.es.js'

I would expect the ESM export to import styleInject from 'style-inject' and style-inject to be included in the package-lock.json as a dependency. What is the correct way of using CSS Modules and injecting into the head for the consumer of a library?

rollup.config.js

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
import json from '@rollup/plugin-json';
import postcss from 'rollup-plugin-postcss';
import pkg from './package.json';
import fg from 'fast-glob';
import path from 'path';

export default [
  {
    input: 'src/index.js',
    external: external(),
    output: [
      {
        name: '@my/packageName',
        file: pkg.module,
        format: 'es',
        sourcemap: true,
      },
    ],
    plugins: [
      {
        name: 'watch-external',
        async buildStart() {
          const files = await fg(['src/index.d.ts', 'playground/**/*']);
          for (let file of files) {
            this.addWatchFile(path.resolve(file));
          }
        },
      },
      json(),
      postcss({
        modules: true,
      }),
      babel({
        exclude: /node_modules/,
        babelHelpers: 'runtime',
        babelrc: false,
        presets: [
          [
            '@babel/preset-env',
            {
              modules: false,
              useBuiltIns: 'entry',
              corejs: 3,
              targets: {
                ie: 11,
              },
            },
          ],
          '@babel/preset-react',
        ],
        plugins: [
          '@babel/plugin-transform-runtime',
          '@babel/plugin-proposal-class-properties',
          '@babel/plugin-proposal-export-namespace-from',
        ],
      }),
      commonjs(),
    ],
  },
];

function external() {
  const { dependencies = {}, peerDependencies = {} } = pkg;

  const externals = [
    ...Object.keys(dependencies),
    ...Object.keys(peerDependencies),
  ];

  return id =>
    // match 'lodash' and 'lodash/fp/isEqual' for example
    externals.some(dep => id === dep || id.startsWith(`${dep}/`));
}

3 Answers

This is not a bug at all. It works properly because stylesInject is just a function from 'styles-inject' package, so we can allow it to be bundled. But it is not bundled because most likely you have this setting in your rollup.config.js:

external: [
    /node_modules/
]

So, replace it with a code bellow and it will work:

external: (id) => {
    if (/style-inject/.test(id)) return false;
    if (/node_modules/.test(id)) return true;
    return false;
},

also, you can write a regexp for it instead

You need to do 2 things:

  • Add style-inject dependency in package.json
    "dependencies": {
        "style-inject": "^0.3.0"
    },
  • Add following plugin to rollup.config.js
const plugins = [
    ...
    {
        /**
         * - https://github.com/egoist/rollup-plugin-postcss/issues/381#issuecomment-880771065
         * - https://lightrun.com/answers/egoist-rollup-plugin-postcss-esm-library-generated-with-rollup-plugin-postcss-throws-cannot-find-module-node_modulesstyle-in
         */
        name: 'Custom Rollup Plugin`',
        generateBundle: (options, bundle) => {
            Object.entries(bundle).forEach((entry) => {
                // early return if the file we're currently looking at doesn't need to be acted upon by this plugin
                if (!entry[0].match(/.*(.scss.js)$/)) {
                    return;
                }

                // this line only runs for .scss.js files, which were generated by the postcss plugin.
                // depending on the use-case, the relative path to style-inject might need to change
                bundle[entry[0]].code = entry[1].code.replace(
                    /\.\.?\/[^\n"?:*<>|]+\/style-inject\/dist\/style-inject.es.js/g,
                    'style-inject',
                );
            });
        },
    }
];

References:

Related