Reputation: 53
I have this:
let avatar = require ('../../../public/assets/img/avatar.jpg');
I want to be able to use something like this:
let avatar = require('alias!./img/avatar.jpg');
What I try to do is set an alias in webpack config like this:
resolveLoader: {
alias: {
'alias': path.join(__dirname, '../public/assets/'),
}
},
Path does resolve to a correct directory and the file is there. The original long require works correctly. But using the alias I get an
Error: Cannot resolve 'file' or 'directory' ./img/avatar.jpg
Am I missing something in alias config or maybe I'm not using the correct tool to achieve this altogether ?
Upvotes: 2
Views: 6358
Reputation: 43068
resolveLoader
is used to resolve loaders, but the path you have given is not a loader.
In webpack, I usually do something like this in resolve.alias
.
resolve: {
alias: {
'@assets': '@/public/assets',
},
}
The above creates an alias for src/public/assets
, using @assets
.
Now you can do:
let avatar = require ('@assets/img/avatar.jpg');
This will allow webpack to resolve it to the correct path.
Upvotes: 2
Reputation: 81
One approach would be to set the modulesDirectories
option, to define a new folder you'd like webpack to resolve paths against.
https://webpack.github.io/docs/configuration.html#resolve-modulesdirectories
Without seeing your webpack.config.js
. I also suspect, you may want to be setting these options to resolve
not resolveLoader
resolve: {
modulesDirectories: [
'path/to/assets'
]
},
and then...
let avatar = require('./img/avatar.jpg');
// should look at 'path/to/assets/img/avatar.jpg'
Upvotes: 0