React Webpack 4 Resolve Alias

一个人想着一个人 提交于 2019-12-23 07:40:08

问题


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!


回答1:


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

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



回答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'.



来源:https://stackoverflow.com/questions/50782230/react-webpack-4-resolve-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!