Making import alias consistent between node and rollup

Viewed 17

I want to configure rollup (via vite) to allow importing with just a hashtag and no slash:

Example:

import logger from '#logger'

I've tried configuring it with this:

{
  '#': resolve(__dirname, 'src'),
  'entries': [{ find: '#', replacement: resolve(__dirname, 'src') }],
},

Both of these however require a trailing slash: #/logger.

The reason I want to remove the slash is because node package.json "imports" requires using # but doesn't seem to work with "#/". I want to have consistent import formats whether I'm programming the back or front end.

My package.json has the following config:

"imports": {
    "#*": "./src/*" // Works
    "#/*": "./src/*" // Doesn't work
  },

Currently I have to do imports like this:

import logger from '#/logger' // frontend
import logger from '#logger' // backend

I don't care which one to use, I just want them to be the same no matter what project I'm developing in. Node seems more restrictive and probably unlikely to be able to configure to use a slash. Is it possible to configure rollup to not require the slash?

1 Answers

Figured it out. Passing it in with regex and optional / slash works:

{ find: /^#/, replacement: `${resolve(__dirname, 'src')}/` }

Note: I did have to manually add a trailing slash to my replacement.

Related