2

I'm building a javascript library and use Babel/Rollup to transpile and bundle it. My library takes advantage of the NodeJS subpath imports. My package.json looks like this:

{
  "name": "mylib",
  "version": "0.0.1",
  ...
  "imports": {
    "#db/*": "./db/*.js"
  }
  ...
}

and in my code, I import internal files as follows:

import db from "#db/connect";

Unfortunately, when I try to bundle my code, I get an Unresolved dependencies error from Rollup. It can't resolve the #db/connect path.

For reference, here is my rollup.config.js:

import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import babel from "rollup-plugin-babel";
import pkg from "./package.json";

export default [
    {
        input: "src/index.js", // entry point
        output: {
            name: "mylib", // package name
            file: pkg.browser,
            format: "umd",
        },
        plugins: [
            resolve(),
            commonjs(),
            babel({
                exclude: ["node_modules/**"],
            }),
        ],
    },
    {
        input: "src/index.js", // entry point
        output: [
            { file: pkg.main, format: "cjs" },
            { file: pkg.module, format: "es" },
        ],
        plugins: [
            babel({
                exclude: ["node_modules/**"],
            }),
        ],
    },
];

How can I tell Rollup to use the subpath imports from the package.json?

Nate
  • 7,606
  • 23
  • 72
  • 124

1 Answers1

0

You are using the old rollup-plugin-node-resolve; to use subpath imports you will need to use the newer @rollup/plugin-node-resolve, at least version 11.1.0 (current version is 15.1.0). You will probably need to upgrade rollup itself accordingly, too.

Also, the Node documentation uses kinda-globs (I think #db/**/*.js would have been more in line with how such paths should be expressed), but as mentioned in node-resolve plugin issue #1077, this particular setup isn't supported by the node-resolve plugin.

Instead, you should specify imports without using any extensions:

  ...
  "imports": {
    "#db/*": "./db/*"
  }
  ...

and then import using full file name including extension in the source code (this would also be more compatible with how things should be done directly in a web browser):

import db from '#db/connect.js';

If you are using VSCode as your IDE, you should additionally have a path setting in jsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "#db/*": ["./db/*"]
    }
  }
}
RolKau
  • 1,737
  • 1
  • 19
  • 18