score:120
Create a file called .env
in the project root and write there:
NODE_PATH=src
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 whether redux
import refers to your app or the library. Instead you can call your folder src/app
and import things from app/...
.
We intentionally don't support custom syntax like @redux
because it's not compatible with Node resolution algorithm.
score:0
None of the answers worked for me. Some didn't work at all and others worked but the import was already inside src
, for example:
import something from 'path/to/file'
.
Whereas I wanted to be able to do:
import something from 'src/path/to/file'
Here is how I solved it:
tsconfig.json
{
"compilerOptions": {
// ...
"baseUrl": ".",
"rootDirs": [
"src"
]
},
"include": [
"src"
]
}
score:1
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!
score:1
in package.json file,
eject this code in the scripts object like this..
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js --env=jsdom",
"eject": "NODE_PATH=src/ react-scripts eject"
},
this will enable the absolute path imports in your app
score:1
The alias solution for craco or rewired create-react-app is react-app-alias for systems as: craco, react-app-rewired, customize-cra
According docs of mentioned systems replace react-scripts
in package.json
and configure next:
react-app-rewired
// config-overrides.js
const {aliasWebpack, aliasJest} = require('react-app-alias')
const options = {} // default is empty for most cases
module.exports = aliasWebpack(options)
module.exports.jest = aliasJest(options)
craco
// craco.config.js
const {CracoAliasPlugin} = require('react-app-alias')
module.exports = {
plugins: [
{
plugin: CracoAliasPlugin,
options: {}
}
]
}
all
Configure aliases in json like this:
// tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"example/*": ["example/src/*"],
"@library/*": ["library/src/*"]
}
}
}
And add this file in extends
section of main typescript config file:
// tsconfig.json
{
"extends": "./tsconfig.paths.json",
// ...
}
score:2
Feb 2010
Wasted about an hour on this.
An example is below:
Goal: Import App.css
in HomePage.js
myapp\src\App.css
myapp\src\pages\HomePage.js
File: jsconfig.json
{
"compilerOptions": {
"baseUrl": "src"
}
}
File: src\pages\HomePage.js
import "App.css";
score:6
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.
resolve: {
modules: ['src/scripts', 'node_modules'],
extensions: ['.jsx', '.js'],
unsafeCache: true,
alias: {
components: path.resolve(__dirname, 'src', 'scripts', 'components'),
utils: path.resolve(__dirname, 'src', 'scripts', 'utils'),
}
}
After that we can import directly in files :
import UiUtils from 'utils/UiUtils';
import TabContent from 'components/TabContent';
score:6
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:
settings: {
'import/resolver': {
node: {
paths: ['src'],
},
},
},
replace 'src' with your folder if you use your own boilerplate with your folder's name.
score:97
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:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
Once you have done this you can then import by specifying subdirectories of "src" (in the following example, components is a subdirectory of src) e.g.
import Button from 'components/Button'
Source: stackoverflow.com
Related Query
- How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app
- React Redux - How to dispatch an action on componentDidMount when using mapDispatchToProps in a connected component
- How to indicate "loading" state for an async action during first render using redux
- How to add action to functional component using Redux and ReactJS
- How to pass Dispatch to action when using redux form
- How do I avoid using separate _PENDING _FULFILLED and _REJECTED actions with redux thunk?
- How to wait for action and API call to complete using redux saga?
- How to dispatch action when a state changes in redux toolkit without using useEffect?
- How to dispatch an action just if another action was correctly dispatched ? Using redux thunk (react)
- When using React / Redux, how is dispatching an action that merely changes the Redux state vs actually doing some task?
- how to match a returned Promise in using Jest with redux action
- How do I avoid infinite loop when using Redux state in useEffect dependency array?
- How to call action in button click of component, Even though i'm using connect function which is not calling in React Redux
- How do I avoid using the && logical operator in mapStateToProps in Redux
- how to avoid undefined data when getting data from redux using useSelector?
- How to redirect to a different page after a redux action using react
- How do I use a relative path to load my images for my website using webpack?
- How to manage submission errors on react final form when using a redux action on onSubmit?
- How to dispatch async action in Redux using Redux Thunk: TypeError: Cannot read property 'loading' of undefined
- How to stub async action in componentDidMount for react redux connected component test using Jest
- How do I avoid 'Function components cannot be given refs' when using react-router-dom?
- How to listen for specific property changes in Redux store after an action is dispatched
- How to dispatch Redux action from stateless component when route is loaded?
- How to divide the logic between Redux reducers and action creators?
- How to use absolute path to import custom scss, when using react + webpack?
- How to dispatch an action when clicking on Link when using React-Router & Redux?
- How to fire periodic actions using setTimeout and dispatcher in redux
- How to reset state of Redux Store when using configureStore from @reduxjs/toolkit?
- How do I resolve 'Property 'type' is missing in type 'AsyncThunkAction' using Redux Toolkit (with TypeScript)?
- how to import LESS files from specific path using webpack less-loader?
More Query from same tag
- How do "componentWillUnmount" work with clearinterval?
- Webpack error: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema
- How to update nested state or values in Typescript and Reactjs?
- How to prevent a form input value from disappearing on click in other fields?
- Not able to fit the Menu width as same as the containers width using material-ui (mui-v5) and reactjs
- How to make images/files downloadable
- I'm having a problem triggering this classlist toggle in React
- How to print a value inside a map returning from a function
- Reactjs, re-render same components, but different return data
- How to create a basic Tooltip in React where you don't actually wrap the anchor element in another DOM element?
- React native-fbsdk unknown issue?
- Showing the distinct values using key property
- How to get the React router path on route change
- Touch Events Broken with ReactJS Upgrade in Chrome Mobile Emulator
- Combining text and JS in className after a ternary operator
- prevstate in react hook
- after updating the state, component is called twice in react-redux, which leads to getting initial state again instead of updated state
- Grpc error while installing Firebase for React
- Cannot send only the filled input with axios on Reactjs
- What is the suitable type for renderHook in react-testing-library and TypeScript?
- React, Single Page Apps, and the Browser's back button
- Passing function to another component getting error this is not defined react js
- Error file is not defined in React (won't export)
- React pass x state variables to y {props.children}
- Meteor-react passing variable to child container
- How to remove Duplicate Object value in an Array in ReactJs
- React Video current length is not updating
- Best way to render HTML emails in React app
- Validation check in reactjs issue
- Change React build path post application build