React Webpack 4 Resolve Alias

Richard Whitehouse picture Richard Whitehouse · Jun 10, 2018 · Viewed 14.3k times · Source

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!

Answer

Richard Whitehouse picture Richard Whitehouse · Jun 10, 2018

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

apiAlias: path.resolve(__dirname, './app/services/api/')