Are you really tired of typing code like this in your React projects?
import { AppContextProvider } from "../../state/State";
import MyComponent from "../../components/MyComponent/MyComponent";
import "./App.css";
Typing those relative paths with directory access dots is cumbersome and confusing. Wouldn't it be great to just do this?
import { AppContextProvider } from "state/State";
import MyComponent from "components/MyComponent/MyComponent";
import "./App.css";
Absolute Imports to the Rescue!
Guess what? You can! Here's how it works. In a create-react-app
project that uses TypeScript, modify your tsconfig.json
file to look like this:
{
"compilerOptions": {
...
"baseUrl": "src"
},
"include": ["src"]
}
Hat tip to Chiamaka Ikeanyi for this suggestion.
Now, restart by doing yarn start
or npm run start
. Tada! Your absolute path imports work perfectly.
But.... (there's always a but), in Visual Studio Code you're seeing:
Well, there MIGHT be a really easy fix for that. Just close and then re-open Visual Studio Code. For most people, that will fix the problem. If not, then open your settings and search for import module specifier
. You'll find one for TypeScript > Preferences > Import Module Specifier
.
If you change this setting to Auto
or Non-relative
, Visual Studio Code will understand how to import modules based on your tsconfig.json
file. You may need to close and reopen the IDE again for it to take effect.
Absolute Imports with Vanilla JavaScript
Haven't embraced TypeScript yet? No problem! You can do the same thing with vanilla JavaScript.
NOTE: I haven't tested this so let me know if it doesn't work.
If you don't already have one, add a .env
file to your working directory. In it add:
NODE_PATH=/src
To read more about it, see : https://medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d
Testing without TypeScript
FYI: The below assumes your are NOT using TypeScript. If you're just using JS, you'll need to do the following:
All is great, right? Unfortunately, you just broke all your tests 😢! The problem is that Jest doesn't know about all this baseUrl
magic.
Thanks to Kent C. Dodds and his excellent Testing JavaScript course, there's a fix for this too!
In your jest.config.js
file, do this:
const path = require("path");
module.exports = {
...
moduleDirectories: ["node_modules", path.join(__dirname, "src")],
};
Now, rerun your tests and all is well!
Let me know if you have any other suggestions for this via Twitter @Calendee