I've been using create-react-app package for creating a react website. I was using relative paths throughout my app for importing components, resources, redux etc. eg, import action from '../../../redux/action
I have tried using module-alis npm package but with no success. Is there any plugin that I can use to import based on the folder name or alias i.e. an absolute path?
Eg., import action from '@redux/action'
or import action from '@resource/css/style.css'
I am using babel-plugin-module-resolver for my project to resolve that problem. babel-plugin-module-resolver also is the same as module-alis. So I think you should just resolve using module-alis problem.
Because you didn't tell us why using module-alis was fail? So i cant show you how to fix it.
Dont give up your solution while you dont know the reason!
The approach in the accepted answer has now been superseded. Create React App now has a different way to set absolute paths as documented here.
To summarise, you can configure your application to support importing modules using absolute paths by doing the following:
Create/Edit your jsconfig.json/tsconfig.json in the root of your project with the following:
Alternatively:
Once you've done this you can then import by specifying subdirectories of "src" (in the following example, components is a subdirectory of src) e.g.
in package.json file,
eject this code in the scripts object like this..
this will enable the absolute path imports in your app
Create a file called
.env
in the project root and write there:Then restart the development server. You should be able to import anything inside
src
without relative paths.Note I would not recommend calling your folder
src/redux
because now it is confusing whetherredux
import refers to your app or the library. Instead you can call your foldersrc/app
and import things fromapp/...
.We intentionally don't support custom syntax like
@redux
because it's not compatible with Node resolution algorithm.After you try Ben Smith's solution above if you find eslint complains about importing absolute path add the following line to your eslint config
replace 'src' with your folder if you use your own boilerplate with your folder's name
We can use webpack 2 resolve property in the webpack config.
Sample webpack config using resolve :
Here component and utils are independent folder containing React components.
After that we can import directly in files :
Webpack 2 Resolve Reference