14

I'm having difficulty getting resolve alias to work in my React app using WebPack, and everything I've tried from google results don't seem to make a difference.

Here is my resolve from webpack.

C:\website\webpack.config.js

resolve: {
    extensions: ['*', '.js', '.jsx'],
    alias: {
        apiAlias: path.resolve(__dirname, '/app/services/api/')
    }
}

Here is C:\website\app\components\Accounts\Accounts.js

import ApiAccounts from '/apiAlias/ApiAccounts.js';

and I have a file located in C:\website\app\services\api\ApiAccounts.js Changing the above line to the below works:

import ApiAccounts from '../../services/api/ApiAccounts.js';

For fullness, here are my webpack dependencies:

"devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.12.0",
    "webpack-cli": "^3.0.3",
    "webpack-dev-server": "^3.1.4"
 }

and yet I keep getting the error of

ERROR in ./app/components/Accounts/Accounts.js Module not found: Error: Can't resolve '/apiAlias/ApiAccounts.js' in 'C:\website\app\components\Accounts'

Can anyone see anything obvious as to what I'm missing, or should try to try and get this working, or even if there is a way to debug webpack to see what path it is actually using if the alias is actually kicking in?

Thanks!

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Richard Whitehouse
  • 679
  • 3
  • 14
  • 28

2 Answers2

14

The only thing I was missing was the dot before /app!

apiAlias: path.resolve(__dirname, './app/services/api/')
Richard Whitehouse
  • 679
  • 3
  • 14
  • 28
  • A bit late, but I don't think that's what solved your issue. Looking at https://nodejs.org/api/path.html#path_path_resolve_paths, path.resolve works fine with or without the '.' prefix. I think Nikita's answer is more likely. – Connor Low Mar 05 '20 at 18:37
2

What you can do is remove the first '/' in your ApiAccounts import:

import ApiAccounts from 'apiAlias/ApiAccounts.js';

This way your import path start with the key in your alias object, which in your case is apiAlias.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98