最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Absolute imports with rollup - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Feb 15, 2018 at 17:11 Adam Rackis asked Feb 15, 2018 at 17:06 Adam RackisAdam Rackis 83.4k57 gold badges278 silver badges400 bronze badges 4
  • why wouldn't the first work in any module? – Liam Commented Feb 15, 2018 at 17:08
  • @Liam because it's a non-relative import – Adam Rackis Commented Feb 15, 2018 at 17:08
  • right so that lives in your root and you want to not do all the ../ stuff? – Liam Commented Feb 15, 2018 at 17:09
  • Right, I want to be able to do import { startup } from "applicationRoot/renderUI"; from any level in my app, and have it work. – Adam Rackis Commented Feb 15, 2018 at 17:10
Add a comment  | 

2 Answers 2

Reset to default 14

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.

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'
发布评论

评论列表(0)

  1. 暂无评论