Moo3
Moo3

Reputation: 172

Why does Webpack throw error when using this resolve.alias config?

Using an alias key which contains substring of another alias results in an error.

//in this given file structure
src
|--app
|   |--module.js
|--component
|   |--module.js
|--config
    |-config.js

//and config
alias: {
     'base': path.resolve('src/config'),
     'base/app': path.resolve('src/app'),
     'base/component': path.resolve('src/component')
}

import app from 'base/config'
works as expected, returns module src/config.js

import app from 'base/app/module'
Module not found: Error: Can't resolve 'base/app/module'

import app from 'base/component/module'
Module not found: Error: Can't resolve 'base/component/module'

Upvotes: 0

Views: 200

Answers (1)

Hawkins
Hawkins

Reputation: 710

I believe this has to do with how webpack's enhanced-resolve AliasPlugin works. By having the other base be an alias and having other aliases start with base/, you're triggering a false positive in this logic that you didn't intend since the path isn't actually below where base points to (for base/app, /src/app is not below /src/config)

So, you could either use another delimiter (_) for this one instance, or better yet set up aliases that behave how Webpack intends just to avoid breaking changes in the future.


So you could replace the / with another character, like so:

alias: {
     'base': path.resolve('src/config'),
     'base_app': path.resolve('src/app'),
     'base_component': path.resolve('src/component')
}

// ...
import app from 'base_app/module'

Or if that's not ideal, you could instead redefine your alias to avoid the issue altogether:

alias: {
     'base': path.resolve('src')
}

// ...
import config from 'base/config'
import app from 'base/app/module'

Upvotes: 1

Related Questions