Webpack: Should I be able to use absolute path imports?

Created on 18 Jul 2017  路  7Comments  路  Source: vuejs-templates/webpack

Hi there,

I'm wondering if I'm supposed to be able to do something like

import ComponentWhatever from 'src/components/ComponentWhatever'

instead of one of these:

import ComponentWhatever from '@/components/ComponentWhatever'
import ComponentWhatever from '../components/ComponentWhatever'

I found the @ alias, but I'm not sure if absolute paths work out-of-the-box. I'm running into issues with my vue-cli-webpack project + Jest, and I think it's because Jest is not translating the @ alias so I'd like to avoid it and just use the absolute path (if possible).

thanks!

Most helpful comment

Well, looks like I fixed my issue with Jest, just missed this regex pattern in my ModuleNameMapper:

"^@[/](.+)": "<rootDir>/src/$1",

I still don't get why I can't just use src/components/Component/ but since the @ alias is working...

All 7 comments

@afontcu, you can do that but I'd recommend usign babel-plugin-module-resolver with Jest instead.

@nickmessing thanks for your time

I have a folder for each component, and I use an index.js files to expose the component:

src/
  components/
    ComponentWhatever/
      index.js
      ComponentWhatever.vue
      ComponentWhatever.spec.js

index.js just import ComponentWhatever from './ComponentWhatever' and then exports it.

to avoid having to type something like

import ComponentWhatever from '../../ComponentWhatever/ComponentWhatever'

When I try to import a component (from another component or from the tests indistinctly) I cannot use the absolute path (src/components/ComponentWhatever). OTOH it is working fine with the @ alias and with relative paths.

Does this even make sense?

Should I use another architecture for my components folder?

Thank you very much!

Well, looks like I fixed my issue with Jest, just missed this regex pattern in my ModuleNameMapper:

"^@[/](.+)": "<rootDir>/src/$1",

I still don't get why I can't just use src/components/Component/ but since the @ alias is working...

@afontcu, for src/ you need to set up resolve.modules in webpack config

Hm, I tried adding

modules: [resolve('src'), 'node_modules']

to my webpack base configuration and absolute paths are still failing. Something else must be wrong... nevermind, since @ is working this is no longer a problem so I'm closing the issue.

Thanks @nickmessing for your time! Appreciate it.

@afontcu, with this config you can import MyComponent from 'components/MyComponent.vue'

@nickmessing finally! Now I understand, I was adding both the module.exports line and also src/ to every import statement. Thanks!

Then I added

"^components[/](.+)": "<rootDir>/src/components/$1",

to the ModuleNameMapper object from my Jest config and components/MyComponent worked fine both in dev and test environments.

Kudos to you! 馃帀

Was this page helpful?
0 / 5 - 0 ratings