Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute imports with rollup

I'm trying to get imports like

import { startup } from "applicationRoot/renderUI";

to work, from anywhere in my application. I thought the rollup-plugin-alias would be a good fit for this. I tried configuring

alias({
  applicationRoot: "applicationRoot/"
})

in my plugins array. This came close, but the extension is dropped, so I get the error:

c:\path\to\applicationRoot\renderUI doesn't exist.

Adding in

alias({
  resolve: [".js"],
  applicationRoot: "applicationRoot/"
}),

did not change anything.

like image 600
Adam Rackis Avatar asked Feb 15 '18 17:02

Adam Rackis


2 Answers

You can use rollup-plugin-includepaths.

Add this to your Rollup configuration:

import includePaths from 'rollup-plugin-includepaths';

export default {
  ...
  plugins: [
    ...
    includePaths({ paths: ["./"] })
  ]
};

That will tell Rollup to also resolve imports from the root of your application, so things like

import { startup } from "applicationRoot/renderUI";

will appropriately find an applicationRoot folder where it is.

like image 82
Michał Perłakowski Avatar answered Nov 11 '22 22:11

Michał Perłakowski


This is not the answer to the original question, but if you are coming here from search results and are using Typescript, you can set the compilerOptions.baseUrl in tsconfig and it will just work.

{
  ...
  compilerOptions: {
    ...
    "baseUrl": "./"
  },
}

Then if you have a file like `src/lib/util.ts' you can import it:

import util from 'src/lib/util'
like image 3
Maciej Krawczyk Avatar answered Nov 11 '22 21:11

Maciej Krawczyk