Setting up a React Monorepo with Yarn Workspaces, TypeScript, and Absolute Imports
If you are experiencing difficulties while setting up a React project with yarn workspaces, TypeScript, and absolute imports, you are not alone. This blog post aims to provide a solution to the common problem of encountering a TypeError when importing .ts or .tsx files from a common project. We will walk through the steps to configure your project correctly and address any missing elements.
Folder Structure
Before delving into the troubleshooting process, let’s ensure that your folder structure follows the recommended setup:
- root
- package.json
- tsconfig.json
- packages
- common
- package.json
- tsconfig.json
- services
- web
- package.json
- tsconfig.json
It is crucial to adhere to this hierarchy as it will facilitate the proper configuration and import resolution.
Configuring package.json
First, let’s modify the root package.json
file to include the necessary workspaces and dependencies:
{
"name": "my-project-name",
"private": true,
"workspaces": [
"packages/*",
"services/**/*"
]
}
Make sure to replace my-project-name
with your project’s actual name. This configuration enables yarn to recognize and manage all packages within the specified folders.
TypeScript Configuration
We also need to configure TypeScript to resolve the imports correctly. In the root tsconfig.json
, add the following:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@myproject/*": ["packages/*/src"]
}
}
}
By setting the baseUrl
to "."
, we ensure that TypeScript searches for imports relative to the root folder. Additionally, the "paths"
property specifies that all imports starting with @myproject/
will be resolved from the src
folders within the packages.
Fixing Import Errors
To resolve the import errors and enable imports from the common package, you need to modify the web/package.json
file:
{
"dependencies": {
"@myproject/common": "*"
}
}
Ensure that the name of the common package in its package.json
is set to "@myproject/common"
. With this configuration in place, you can import code from the common package within the web package using the following syntax:
import { myUtilFunction } from "@myproject/common";
Conclusion
By following the steps outlined in this post, you should be able to successfully set up a React project with yarn workspaces, TypeScript, and absolute imports. Remember to adhere to the recommended folder structure, configure the package.json and tsconfig.json files accordingly, and resolve any import errors by adding the necessary dependencies. If you encounter any further issues, I recommend referring to the provided example repository and exploring additional learning resources.
Happy coding!