ozys5000
ozys5000

Reputation: 53

Using webpack resolveLoader alias or how to shorten require path

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

Answers (2)

smac89
smac89

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

oller
oller

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

Related Questions