Background
I have a React app bootstrapped using create-react-app
and typescript. As the application has grown, (goal) I would like to implement absolute imports. I am using VS Code (Visual Studio Code) and with very little configuration, I got TS and VS Code to recognize my absolute imports.
For TS, I took the following steps in my tsconfig.json
:
- Change the 'baseUrl' to 'client':
"baseUrl": "client"
- Added 'client' to my
include
key:"include": ["./**/*.ts", "./**/*.tsx", "client"]
For VS Code, I changed my User Settings: Typescript -> Preferences: Import Module Specifier -> non-relative
That worked great. All of my imports were using absolute imports, no errors. But, when I ran the app, I got an error: Error: Cannot find module "component"
I expected to see my app like I did before the absolute imports.
What I Tried
Figured, the error was a webpack or babel issue.
Created
env
FileAdded the following to an env file in the root of the app (same location as my package.json)
NODE_PATH=client/
That did not work. Same error: Error: Cannot find module "components"
. Also tried changing NODE_PATH to REACT_APP_NODE_PATH that did not work either.
Modify Babel Config
Added babel plugin module resolver with
yarn add -D babel-plugin-module-resolver
. Then modified mybabel.config.js
to:
module.exports = {
env {...},
plugins: [
[
'module-resolver',
{
cwd: 'babelrc',
extensions: ['.ts', '.tsx', '.js'],
alias: {
client: './client',
},
},
],
]
}
That returns the same error. (I am restarting the server after every change to my config files)
Resources Referenced I used a lot of different articles to try to find clarity. Here are some:
- Absolute Imports with Create React App by Kyle Truong (here)
- Absolute Imports in Create React App by Michael Bednarz (here)
- Configuring React Absolute Imports For TypeScript by Justin Noel (here)
- Use absolute path in React components (StackOverflow)
- How to import js modules (with absolute path) in my typescript file in React application?
And many others. None of that worked.
Project Structure
My project structure is a little "unconventional" or not my typical pattern which could be causing an issue.
└── root dir
├── assets
│ └── client
│ ├── assets
│ ├── components
│ ├── hooks
│ └── ...
│ └── babel.config.js
│ └── .babelrc
│ └── webpack.config.js
│ └── package.json
└── server files (no server dir)
So client
is like my src
in a typical react app. assets
is the "entry dir" for my server which is in the root dir
.
Any help would be appreciated.