Ivan
Ivan

Reputation: 6013

Why are aliases not resolved correctly with my config?

I have a following resolve option in my webpack config:

resolve: {
    modules: ["./app/static/js/homepage/", "./app/static/js/dashboard/",],
    extensions: [".js", ],
    alias: {
        "bootstrap": "../../bower_components/bootstrap/dist/js/bootstrap",
        "lodash": "../../bower_components/lodash/lodash",
    // ...

But i get this error:

ERROR in ./app/static/js/dashboard/main.js
Module not found: Error: Can't resolve 'underscore' in '/app/app/static/js/dashboard'
 @ ./app/static/js/dashboard/main.js 84:0-112:2

Which means it doesn't treat underscore as an alias, which happens to all defines in my project.

Upvotes: 0

Views: 244

Answers (1)

Michael Jungo
Michael Jungo

Reputation: 32992

You are aliasing them to a relative path and you go up two directories (with ../../), so when you import lodash in./app/static/js/dashboard/main.js, it will try to find the module in

./app/static/bower_components/lodash/lodash

Assuming that your bower_components are in the top level of the project (as it is recommended), you can fix the aliases by going up four directories:

alias: {
  "bootstrap": "../../../../bower_components/bootstrap/dist/js/bootstrap",
  "lodash": "../../../../bower_components/lodash/lodash",
}

Note, this will only work if you import them in a file that is four levels deep. Replacing them with absolute paths would work everywhere.

An even cleaner solution is to add bower_components to your modules, so it looks in every bower_component directory, which is the common way to integrate bower into webpack. With that you could just use import _ from 'lodash/lodash' without adding any aliases. But if you'd still like to have an alias you could do it as follows:

resolve: {
  modules: ["bower_components"],
  extensions: [".js"],
  alias: {
    "bootstrap": "bootstrap/dist/js/bootstrap",
    "lodash": "lodash/lodash",
  }
}

Upvotes: 1

Related Questions