This article is about fixing Add baseUrl and paths in tsconfig.json and jsconfig.json in Facebook Create React App
  • 30-Jan-2023
Lightrun Team
Author Lightrun Team
Share
This article is about fixing Add baseUrl and paths in tsconfig.json and jsconfig.json in Facebook Create React App

Add baseUrl and paths in tsconfig.json and jsconfig.json in Facebook Create React App

Lightrun Team
Lightrun Team
30-Jan-2023

Explanation of the problem

The tsconfig.json or jsconfig.json file is a configuration file used to define the compiler options for TypeScript and JavaScript projects. The file is commonly used by text editors like Visual Studio Code to resolve the project’s paths.

Configuration of compilerOptions and baseUrl:

In the tsconfig.json or jsconfig.json file, the compilerOptions object contains the configuration for the TypeScript or JavaScript compiler. The baseUrl property, which is set to “.”, is used to define the root directory for relative path resolution.

CompilerOptions:

"compilerOptions": {
  "baseUrl": ".",
  ...
}

The paths property is an object that maps a virtual path to a real file path. In this case, “@/” is a virtual path that is mapped to “src/“. This mapping helps the compiler to resolve the actual location of the imported modules in the code.

"paths": {
  "@/*":["src/*"]
}

Note: For more information on using tsconfig.json or jsconfig.json, see the issue raised on the create-react-app repository on GitHub: https://github.com/facebook/create-react-app/issues/5118.

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for Add baseUrl and paths in tsconfig.json and jsconfig.json in Facebook Create React App

Understanding the Problem The problem arises when trying to resolve absolute import paths in TypeScript and JavaScript projects, particularly with VSCode and other IDEs. This issue is caused by the fact that without proper configuration, the IDE does not know how to resolve the paths to the imported modules, leading to intellisense errors and issues with building and testing the code.

Workaround Solution One approach to resolving this issue is to set the desired configurations in a separate .json file, and then use the extends feature of tsconfig.json. Although this approach generates a warning, it does not override the settings and allows for the code to be tested and built without any issues. For example, you can set the following configurations in a paths.json file:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "svg/*": ["src/svg/*"],
      "components/*": ["src/components/*"]
    }
  }
}

And in the tsconfig.json file, include the following line:

{
  "extends": "./paths.json"
}

Alternative Solution Another approach to resolving this issue is to use the .env file and tsconfig.paths.json file. By setting the NODE_PATH environment variable in the .env file to ./, and including the following configurations in the tsconfig.paths.json file:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "src/*": ["*"]
    }
  }
}

And then adding the following line at the end of the generated tsconfig.json file:

"extends": "./tsconfig.paths.json"

This approach allows for absolute import support using the src/ prefix, without any customizations. The src/ prefix provides explicit and easily recognizable import paths, and works out-of-the-box with the NODE_PATH environment variable, including with jest tests. Additionally, this approach can be reused for non-TypeScript projects by using a jsconfig.json file.

Other popular problems with Create React App

Problem: Absolute Path Imports

A common issue with Create React App (CRA) is the lack of support for absolute path imports, making it difficult to manage file paths in larger projects. This often results in relative file paths becoming increasingly complex and hard to maintain.

Solution:

A solution to this problem is to add a .env file to the project that sets the NODE_PATH environment variable to the root of the project. Next, a tsconfig.paths.json file can be added that specifies the base URL as “src”. This allows for absolute path imports to be used in the project.

Here is an example of the .env file:

NODE_PATH=./

And here is an example of the tsconfig.paths.json file:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "src/*": ["*"]
    }
  }
}

Finally, add the following line at the end of the generated tsconfig.json:

"extends": "./tsconfig.paths.json"

This solution should work with both TypeScript and JavaScript projects and enables the use of absolute imports, allowing for cleaner and more manageable file paths.

Problem: Lacking Support for LESS or SASS

Another issue with CRA is the lack of built-in support for LESS or SASS preprocessors. This can be a challenge for developers who prefer to use these preprocessors for styling their projects.

Solution:

To solve this problem, developers can install and configure the necessary packages to support LESS or SASS. For LESS, the less-loader and less packages can be installed and added to the webpack configuration. For SASS, the node-sass and sass-loader packages can be installed and added to the webpack configuration.

Here is an example of installing and configuring the less-loader and less packages for LESS:

npm install --save-dev less less-loader

And here is an example of the webpack configuration for LESS:

module: {
  rules: [
    {
      test: /\.less$/,
      use: [
        {
          loader: 'style-loader',
        },
        {
          loader: 'css-loader',
        },
        {
          loader: 'less-loader',
          options: {
            lessOptions: {
              javascriptEnabled: true,
            },
          },
        },
      ],
    },
  ],
},

Problem: Custom Environment Variables

Create React App does not allow environment-specific variables, such as API_KEY, to be stored in the codebase. Instead, the recommended way is to set these variables in the environment where the app runs, such as a production environment, which can lead to security risks.

Solution:

A common solution is to create a .env file in the root directory of the project, which can store environment-specific variables. The .env file is not version controlled, so it is not part of the codebase and can be used to store sensitive information. The variables stored in the .env file can be accessed by the codebase using the process.env object.

For example, let’s say you want to store the API key for your application in the .env file.

.env:

API_KEY=your_api_key

And you can access the API key in the codebase like this:

const apiKey = process.env.API_KEY;
console.log(apiKey); // prints "your_api_key"

A brief introduction to Create React App

Create React App (CRA) is a popular command line tool for setting up a new React project with a basic configuration and development environment. CRA is maintained by Facebook and is widely used by React developers as a way to quickly get started with a new project. It is also fully customizable, making it possible to extend the basic configuration with additional features.

CRA takes care of a number of common setup tasks for you, such as setting up a development server, handling transpilation and bundling of your code, and setting up a basic directory structure for your project. CRA is designed to work with zero configuration, so you can start building your React application right away. Additionally, CRA is updated regularly to ensure that it is compatible with the latest versions of React, so you can be confident that your project is using the latest tools and features.

Most popular use cases for Create React App

  1. Building Single Page Applications (SPAs) – Create React App is specifically designed to make it easy to build SPAs using React. This means that you can use CRA to quickly create applications that run in the user’s browser, providing a rich and interactive user experience.
  2. Developing Progressive Web Apps (PWAs) – Progressive Web Apps are web applications that provide a native-like experience on the web. With Create React App, you can easily build PWAs that work offline, are installable on the user’s home screen, and can be launched like native apps.
import React, { useState } from "react";
import {
  BrowserRouter as Router,
  Route,
  Link,
  Switch,
  useHistory,
  useLocation
} from "react-router-dom";

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/users">Users</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

export default App;
  1. Debugging and Testing React Applications – Create React App provides a number of tools to make it easy to debug and test your React code. For example, it automatically sets up a development server for you, making it easy to test your application in a browser. It also includes a test runner, Jest, which makes it easy to write and run tests for your React components. Additionally, Create React App includes a set of default scripts that make it easy to run tests and validate your code, ensuring that it is working correctly.
Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.