Add absolute paths to app created by "Create React App" - reactjs

I have created an app by Create React App and to be more specific I'm also using typescript.
I can't figerout how to set absolute paths to access to my components, pages, etc..
In a different scenario I would update my tscongig with something like:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#components/*": ["src/components/*"]
}
}
}
but I have no idea how to implement this as I'm using react-scripts
any idea?

Create a tsconfig.json file and add the code below.
{
"compilerOptions": {
"baseUrl": "src"
},
"include": [
"src"
]
}
Then you can import your components as
import Header from 'components/Header';

You should be able to use the same approach if create a jsconfig.json file in your solution, which supports the same baseUrl and rootPath properties as tsconfig.
Alternative is adding an .env file in your solution with the following line:
NODE_PATH=src/
Also, apart from the env file add this to your jsconfig.json
{
"rootDir": "src",
"compilerOptions": {
"baseUrl": "src",
"paths": {
"*": ["*"]
}
}
}
This should resolve both the compiler being able to find your absolute imports, and linter handling them properly.

See Building Your App / Importing a Component / Absolute Imports in the Create React App docs.
You can configure your application to support importing modules using absolute paths. This can be done by configuring a jsconfig.json or tsconfig.json file in the root of your project. If you're using TypeScript in your project, you will already have a tsconfig.json file.
Below is an example jsconfig.json file for a JavaScript project. You can create the file if it doesn't already exist:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
If you're using TypeScript, you can configure the baseUrl setting inside the compilerOptions of your project's tsconfig.json file.
Now that you've configured your project to support absolute imports, if you want to import a module located at src/components/Button.js, you can import the module like so:
import Button from 'components/Button';

Related

React Nextjs - module import using # no longer working

I was able to import modules using # but I upgraded a few components including react and nextjs.
this used to work
import { ValidateProps } from '#/api-lib/constants';
Now getting error:
Module not found: Can't resolve '#/api-lib/constants'
It works if I give it a path
import { ValidateProps } from '../../api-lib/constants';
Personally, I use a jsconfig.json file. It contains:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
Then I am able to import like so:
import Loadable from "components/ui/Loadable";
I just figured I no longer had jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#/api-lib/*": ["api-lib/*"],
}
}
}

jsconfig.json path alias not working properly

I have a react project created using create-react-app, and I'm trying to add material kit react to the project. I have placed the assets and components of material kit react under src/template and I would like to change the path of assets from src/assets to src/template/assets.
The problem is when I configured jsconfig.json to define the path for assets alias I get the error "Module not found" when using assets, but if I use the template alias it works just fine.
Here is my jsconfig.json file:
{
"compilerOptions": {
"baseUrl": "src",
"target": "es6",
"paths": {
"template/*": ["src/template/*"],
"assets/*": ["src/template/assets/*"]
}
},
"exclude": ["node_modules"]
}
If someone can help me to understand why the template alias is working and not the assets alias.
please try the code below.
I think your 'baseUrl' is wrong.
{
"compilerOptions": {
"baseUrl": ".",
"target": "es6",
"paths": {
"template/*": ["./src/template/*"],
"assets/*": ["./src/template/assets/*"]
}
},
"exclude": ["node_modules"]
}
So, This will make VS Code IntelliSense work.
But there may be other issues. (..Because I went through it.)
Other issue is that resolve does not work.
error is the same
This dependency was not found:
* template/somtething in ./blahblah..
To install it, you can run: npm install --save template/somtething`
If there is an error above,
try to set an alias to the 'template' folder using the following Webpack configuration.
https://webpack.js.org/configuration/resolve/

Visual studio code: navigate to jsx components

In visual studio code, I would like to be able to navigate to an imported file using ctrl + click.
So far I'm able to do it for javascript files (.js), but it's not working for react files (.jsx)
Here is what my directory structure looks like :
Here are the imports (relative and absolute) in my TestImport.jsx Component :
import DummyTwo from 'components/common/dummy-two/DummyTwo.jsx';
import something from 'components/common/my-file/myFile.js';
import DummyOne from '../common/dummy-one/DummyOne.jsx';
import somethingElse from '../common/my-file/myFile2.js';
And here is my jsconfig.json for vscode
{
"compilerOptions": {
"experimentalDecorators": true,
"baseUrl": "src"
}
}
Code can be retrieved here:
https://github.com/fthebaud/react-boilerplate
Am I missing something in the jsconfig file? regarding the extensions maybe?
You need to add "jsx": "react" to use jsx:
{
"compilerOptions": {
"experimentalDecorators": true,
"baseUrl": "src",
"jsx": "react"
}
}
See here for more info about this setting

How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app

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'
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.
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'
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';
Webpack 2 Resolve Reference
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.
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";
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",
// ...
}
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!
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
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"
]
}

Import react components with absolute path

Here is my test file
// /imports/components/main.test.js
import React from 'react'
import { shallow, mount } from 'enzyme'
import Main from './main'
import TextInput from "/imports/ui/textInput"
...
and the main.js has
// /imports/components/main.js
import { action1 } from "/imports/actions/myAction"
but it throws an error when I run the test, saying
Cannot find module '/imports/actions/myAction' from 'main.js'
If I comment the import './main', same thing happen with importing TextInput. I have no issue with importing modules in node_modules.
How can I tell Jest or webpack to import the component using absolute path from project directory (i.e import Foo from /imports/...)?
Better way to solve relative path import issue, is by creating jsconfig.json file adjacent to package.json file.
{
"compilerOptions": {
"baseUrl": "src"
}
}
then import { action1 } from "actions/myAction"; will work
If you're using Create React App, you can set up the absolute imports path in a jsconfig.json (need to create in a fresh JavaScript template) or tsconfig.json (already created in the TypeScript template) at the root of your project to serve your usage.
Example:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
Official docs: https://create-react-app.dev/docs/importing-a-component/#absolute-imports
Another solution is to create an .env file within the root directory of your project.
Within it you will add NODE_PATH=src/
Thats all
Save the file and restart your dev environment in terminal.
Afterwards, you will go through your project and update some import statements accordingly.
My file structure follows exactly the same pattern as yours. To teach Jest into using imports beginning with a /, I use babel-plugin-module-resolver and its handy root option. My .babelrc for Jest looks like this:
{
"presets": ["es2015", "meteor"],
"plugins": [
"transform-class-properties",
"transform-react-constant-elements",
"transform-react-inline-elements",
"transform-react-remove-prop-types",
["module-resolver", {
"root": ["../"],
"alias": {
"react-router-dom": "react-router-dom/umd/react-router-dom.min.js",
"redux": "redux/dist/redux.min.js",
"react-redux": "react-redux/dist/react-redux.min.js"
}
}]
]
}
As I'm using Meteor which customized its root imports, I hide my Jest usage and configuration into a .jest directory at the root of my repository allowing me to have a specific .babelrc without risking conflicts with Meteor's one.
With webpack(v4) and babel, you can provide absolute paths in your directory.
Follow these steps
In your .babelrc file, make this entry for plugins.Make sure you have babel-plugin-root-import in your package.json as well.
"plugins": [
[
"babel-plugin-root-import",
{
"paths": [
{
"rootPathPrefix": "~",
"rootPathSuffix": "./"
},
{
"rootPathPrefix": "#src",
"rootPathSuffix": "src"
},
{
"rootPathPrefix": "#any-other-folder",
"rootPathSuffix": "src/client/../any-other-folder"
}
]
}
]
]
Now if you run into eslint issue, you can add these lines in your eslintrc:
"settings": {
"import/resolver": {
"babel-plugin-root-import": [
{
"rootPathPrefix": "#src",
"rootPathSuffix": "src"
},
{
"rootPathPrefix": "#any-other-folder",
"rootPathSuffix": "src/client/../any-other-folder"
}
]
}
}
Now to make your editor recognize these paths, you can create this entry in jsconfig file.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["/*"],
"#src/*": ["src/*"],
"#any-other-folder/*": ["src/client/../any-other-folder/*"] ==> absolute path to any other folder
}
},
"exclude": ["node_modules"]
}
Hope these entries help.
I had jest configs in package.json file (under "jest" key). So I just have added there this row:
"modulePaths": ["<rootDir>/src/"]
And this works for me. I hope it can help somebody else.

Resources