Troubleshooting Common Issues in Facebook Create React App
Project Description
Create React App is a tool developed by Facebook that allows developers to create and set up a new React project with a single command. It provides a modern build setup with no configuration, so developers can get started writing code right away. Create React App is a great tool for developers who are new to React and want to get started quickly, or for experienced developers who want a simple, easy-to-use development environment. It is designed to be easy to use and set up, with no build configuration required.
Create React App comes with a number of features out of the box, including:
- A development server with hot module reloading
- A production build script with minification and tree shaking
- Support for JSX and ES6 syntax
- Automatic code formatting with Prettier
- Linting with ESLint
Troubleshooting Facebook Create React App with the Lightrun Developer Observability Platform
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
The following issues are the most popular issues regarding this project:
WebSocket connection to ‘ws://localhost:3000/ws’ failed:
If you are seeing the error “WebSocket connection to ‘ws://localhost:3000/ws’ failed” when running a Create React App project, it could be due to a problem with the way the WebSocket connection is being established.
Here are a few things you can try to troubleshoot this issue:
- Make sure that the WebSocket server is running and is listening on the correct port (
3000
in this case). You can check the logs of the WebSocket server to see if there are any errors or issues that might be causing the connection to fail. - Check the network configuration of your development environment to make sure that there are no firewall rules or other restrictions that might be blocking the WebSocket connection.
- Make sure that the URL of the WebSocket connection is correct. The URL should include the correct protocol (
ws
orwss
), the correct hostname (localhost
in this case), and the correct port number (3000
in this case). - Check the browser console for any error messages that might provide more information about the cause of the problem.
Error:0308010C:digital envelope routines::unsupported
The error “Error:0308010C:digital envelope routines:unsupported” typically occurs when there is a problem with the way cryptographic keys are being used.
This error can have a number of different causes, including:
- An unsupported cryptographic algorithm is being used. Make sure that the algorithm you are using is supported by your environment and is configured correctly.
- There is an issue with the cryptographic keys being used. Make sure that the keys are valid and have not been compromised.
- There is a problem with the way the keys are being used. Make sure that the keys are being used correctly and that the correct key is being used for the intended operation.
- There is a problem with the way the cryptographic library is being used. Make sure that the library is being used correctly and that all necessary dependencies are installed.
To fix this issue, you will need to troubleshoot the specific cause of the problem. This may require reviewing your code and configuration, checking the logs of your application or server, and examining any relevant error messages.
Run Lint from the command line?
In a Create React App project, you can run the linter from the command line by using the npm run lint
or yarn lint
command. This will run the linter on all of the JavaScript and TypeScript files in your project, and will print any linting errors or warnings to the console.
By default, Create React App uses ESLint to lint your code. You can configure the linter by creating a file called <strong>.eslintrc</strong>
in the root of your project and adding your desired configuration options to the file. For example, you can specify the rules that the linter should use, or configure the linter to ignore certain files or directories.
Here is an example of a basic .eslintrc
file that configures the linter to use the Airbnb style guide:
{
"extends": "airbnb"
}
You can also run the linter in “fix” mode, which will automatically fix any fixable linting errors. To do this, use the npm run lint:fix
or yarn lint:fix
command.
Can’t import the named export ‘XXX’ from non EcmaScript module (only default export is available)
It looks like you are trying to import a named export from a module, but the module only has a default export. In JavaScript, a module can have both named and default exports.
To import a named export, you need to use the import { name } from 'module'
syntax. If the module only has a default export, you can use the import name from 'module'
syntax to import the default export.
For example, if you have the following module:
export default function foo() {
// ...
}
You can import the default export like this:
import foo from './foo';
If the module has both a default export and named exports, you can import the named exports like this:
import foo, { bar, baz } from './foo';
You can also use the import * as name from 'module'
syntax to import all of the exports from a module into a single object.
For example:
import * as foo from './foo';
This will create an object foo
with all of the exports from the ./foo
module as properties on the object. You can then access the named exports like this: foo.bar
, foo.baz
, etc.
v5 used to include polyfills for node.js core modules by default
Yes, that’s correct. Prior to version 5, Create React App included polyfills for several Node.js core modules by default, including process
, global
, and Buffer
. This allowed you to use these modules in your code without having to worry about whether the target environment supported them.
Starting with version 5, Create React App no longer includes these polyfills by default. Instead, it relies on the built-in
mode in the @babel/preset-env
configuration to automatically detect whether the target environment supports the features your code uses and only include the necessary polyfills.
If you want to include polyfills for specific Node.js core modules, you can do so by installing the corresponding npm packages and importing them in your code. For example, to include a polyfill for the process
module, you can install the process-polyfill
package and then import it like this:
import 'process-polyfill';
Alternatively, you can use the @babel/polyfill
package to include a broad set of polyfills for many of the features that are missing in older browsers. This package is not included by default in Create React App, so you will need to install it yourself if you want to use it.
To use the @babel/polyfill
package, you will need to import it at the top of your entry point file (e.g., index.js
or main.js
).
import '@babel/polyfill';
Keep in mind that the @babel/polyfill
package is quite large and may significantly increase the size of your bundle, so you should only include it if you actually need the features it provides.
React npm start con’t run and open the localhost:3000
There could be a few different reasons why the npm start
command is not running the development server and opening the localhost:3000 in your Create React App project. Here are a few things you can try to troubleshoot the issue:
- Make sure you have the latest version of Node.js and npm installed on your machine. Create React App requires at least Node.js version 10.13.0 and npm version 6.4.1 to run.
- Run the
npm install
command to install all of the project’s dependencies. This step is necessary whenever you clone a project or pull in updates from version control. - If you recently made changes to the project, try running the
npm start
command again after reverting the changes. This will help you determine if the issue is caused by your changes or something else. - Check the console for error messages. The development server will log any issues it encounters while starting up, and these error messages can give you a clue as to what is going wrong.
- If the development server is already running and you are unable to access the localhost:3000, it’s possible that another process is already using the port. In this case, you can either stop the other process or use a different port by setting the
PORT
environment variable. For example, you can start the development server on port 3001 like this:PORT=3001 npm start
. - If none of these suggestions help, you may want to try deleting the
node_modules
directory and runningnpm install
again to reinstall all of the dependencies. You may also want to try deleting thepackage-lock.json
file and runningnpm install
again.
Multiple errors Module not found: Error: Can’t resolve path, buffer, stream during upgrade to react-scripts 5.0.0
Here are a few things you can try to resolve this issue:
- Make sure you have the latest version of Node.js installed on your machine. React requires Node.js version 10.13 or higher.
- Check your package.json file and make sure that the dependencies are correctly listed. In particular, make sure that react-scripts is listed as a dependency.
- Try running
npm install
oryarn install
to install any missing dependencies. - If you’ve recently changed the dependencies or configuration in your project, try running
npm start
oryarn start
with the--reset-cache
flag. This will clear the cache for the development server and rebuild the project from scratch. - If none of these solutions work, try deleting the node_modules directory and running
npm install
oryarn install
again to reinstall all of the dependencies.
Module parse failed: Unexpected token
It looks like you’re encountering a problem with a JavaScript file in your React application. The error message “Module parse failed: Unexpected token” usually indicates that the JavaScript parser has encountered a character that it wasn’t expecting, and it is unable to continue parsing the file.
There are several potential causes for this error:
- You may have a syntax error in your code. This could be a missing or extra character, or a typo. You can try using a tool like ESLint to automatically find syntax errors in your code.
- You may be trying to import a file that is written in a language that is not JavaScript. For example, you might have an import statement like
import './style.css'
, which would cause this error if the file ‘style.css’ is not a valid JavaScript module. - You may be using a JavaScript language feature that is not supported by the version of Node.js or the JavaScript runtime that you are using. For example, if you are using a function like
import()
that is only supported in newer versions of JavaScript, you will need to use a runtime that supports this feature.
DeprecationWarning: ‘onAfterSetupMiddleware’ option is deprecated
It looks like you are seeing a deprecation warning when using create-react-app. This warning is letting you know that the onAfterSetupMiddleware
option has been removed and is no longer supported.
If you are using this option in your code, you will need to remove it to avoid seeing this warning. You may also want to consider updating to the latest version of create-react-app, as it may include other fixes and improvements.
ReferenceError: Cannot access ‘varName’ before initialization
It looks like you are encountering a ReferenceError
when using create-react-app. This error is usually caused by trying to access a variable before it has been initialized.
Here are a few things you can try to fix this error:
- Make sure you have declared the variable before you try to use it.
- If you are trying to access a variable that is declared in a different scope, make sure you are using the correct variable name and that it is in the correct scope.
- If you are using a
let
orconst
variable, make sure you have not re-declared the variable with the same name in the same block.
Add baseUrl and paths in tsconfig.json and jsconfig.json
If you want to add baseUrl
and paths
options to your project’s tsconfig.json
and jsconfig.json
files, you can do the following:
- In your project’s root directory, open the
tsconfig.json
file in a text editor. - Under the
compilerOptions
key, add abaseUrl
key with the value set to the directory where your project’s source files are located. For example:
"compilerOptions": {
"baseUrl": "src"
}
- Under the
compilerOptions
key, add apaths
key with an object that maps the path aliases you want to use to the directories where the corresponding source files are located. For example:
"compilerOptions": {
"baseUrl": "src",
"paths": {
"components/*": ["components/*"]
}
}
This will allow you to use the components/*
alias to refer to files in the src/components
directory.
To add the baseUrl
and paths
options to your jsconfig.json
file, you can follow the same steps. Just make sure to open the jsconfig.json
file and add the options under the compilerOptions
key.
react-scripts fails to build project with Node 17
This could be caused by a few different things. Here are a few things you can try to fix this issue:
- Make sure you are using the latest version of
react-scripts
. Updating to the latest version may fix any issues caused by outdated dependencies. - If you are using a version of
react-scripts
that is compatible with Node 17, try deleting your project’snode_modules
directory and runningnpm install
again to reinstall the dependencies. - If you are using a version of
react-scripts
that is not compatible with Node 17, try downgrading to a version that is compatible. You can check thereact-scripts
package’s documentation to see which versions are compatible with which versions of Node. - If you are using a custom version of Node, try using the version of Node that is recommended by
react-scripts
. You can check thereact-scripts
package’s documentation to see which version of Node is recommended.
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed – JavaScript heap out of memory -\node_modules\typescript\lib\typescript.js
This error can occur when the Node.js process runs out of memory while trying to build or run your project.
Here are a few things you can try to fix this issue:
- Try increasing the amount of memory available to the Node.js process. You can do this by running the
node
command with the--max-old-space-size
flag, followed by the maximum amount of memory you want to allow the process to use. For example:
node --max-old-space-size=4096 my-script.js
- If you are using
react-scripts
to build or run your project, you can also try increasing the amount of memory available to the process by setting theNODE_OPTIONS
environment variable in yourpackage.json
file. For example:
"scripts": {
"start": "NODE_OPTIONS='--max-old-space-size=4096' react-scripts start"
}
- If you are using a version of
react-scripts
that is outdated, try updating to the latest version. This may fix any issues caused by outdated dependencies. - If the issue persists, you may want to try optimizing your code to reduce the amount of memory it requires. This could involve reducing the size of your dependencies, minimizing the use of large data structures, and using lazy loading or code splitting to reduce the amount of code that needs to be loaded at once.
Help, `npm audit` says I have a vulnerability in react-scripts!
If npm audit
is reporting a vulnerability in react-scripts
, it is important to address the issue as soon as possible to ensure the security of your project.
Here are a few steps you can take to fix the vulnerability:
- Run the
npm audit fix
command to automatically fix the vulnerabilities that can be fixed. This command will install any updated packages and dependencies that are required to fix the vulnerabilities. - If the
npm audit fix
command is unable to fix the vulnerability, you may need to manually update the package that is causing the issue. You can do this by running thenpm update
command followed by the name of the package. For example:
npm update react-scripts
- If the vulnerability is in a package that is not directly managed by your project (e.g., a dependency of a dependency), you may need to update the dependency that is using the vulnerable package. You can do this by running the
npm update
command followed by the name of the dependency. - If the vulnerability cannot be fixed by updating packages, you may need to remove the vulnerable package from your project and find an alternative that does not have the vulnerability.
Failed to load plugin ‘@typescript-eslint’ declared in ‘.eslintrc » eslint-config-react-app#overrides[0]’: Cannot find module ‘typescript’
It looks like you are encountering an error when trying to load the @typescript-eslint
plugin in your create-react-app project. This error is usually caused by the typescript
module not being installed in your project.
To fix this issue, try installing the typescript
module by running the following command in your project’s root directory:
npm install typescript
If the typescript
module is already installed and you are still seeing this error, it may be caused by a broken symlink or an issue with your project’s dependencies. In this case, try deleting your project’s node_modules
directory and running npm install
again to reinstall the dependencies.
Inconsistent “Relative imports outside of src/” restriction ?
If you are seeing an “Inconsistent” error when trying to use relative imports outside of the src/
directory in a create-react-app project, it may be because you are using a version of react-scripts
that has stricter rules for managing relative imports.
To fix this issue, you can try one of the following solutions:
- If you want to import a file from outside the
src/
directory, you can use an absolute import instead of a relative import. For example:
import MyModule from '/path/to/MyModule';
- If you want to continue using relative imports, you can try adding the
.
(current directory) symbol to the beginning of your import path. For example:
import MyModule from './../../MyModule';
- If you are using a custom version of
react-scripts
, you may be able to disable the relative import restriction by adding the"eslintConfig": {"extends": "react-app"}
field to your project’spackage.json
file.
npm WARN config global `–global`, `–local` are deprecated. Use `–location=global` instead.
It looks like you are seeing a warning message when using the npm
command with the --global
or --local
flags in a create-react-app project. This warning is letting you know that these flags are deprecated and have been replaced with the --location
flag.
To fix this warning, you can update your npm
command to use the --location
flag instead of the --global
or --local
flags. For example:
npm install --location=global my-package
This will install the my-package
package globally on your system.
Create-react-app stuck on v4.0.3, cannot create a new app
If you are unable to create a new create-react-app project and are stuck on version 4.0.3, there could be a few different issues causing the problem. Here are a few things you can try to fix it:
- Make sure you have the latest version of
create-react-app
installed. You can check the version you have installed by running the following command:
npx create-react-app --version
If the version is lower than the latest release, you can update create-react-app
by running the following command:
npm install -g create-react-app
- If you have the latest version of
create-react-app
installed and are still having issues, try deleting the globalcreate-react-app
package and reinstalling it. You can do this by running the following commands:
npm uninstall -g create-react-app
npm install -g create-react-app
- If the issue persists, try clearing the npm cache by running the following command:
npm cache clean --force
This will delete all of the cache files in your npm
directory, which may resolve any issues caused by corrupted cache files.
import ReactComponent from svg file is not working
If you are trying to import an SVG file as a React component in a create-react-app project and it is not working, there could be a few different issues causing the problem. Here are a few things you can try to fix it:
- Make sure that the SVG file is correctly exported as a React component. You can do this by wrapping the contents of the SVG file in a
<svg>
element, and then using theReact.createElement
function to create a new React component. For example:
import * as React from 'react';
function MySvg() {
return (
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
{/* SVG content goes here */}
</svg>
);
}
export default MySvg;
- Make sure that the file path to the SVG file is correct in your import statement. If the file path is incorrect, the import will fail.
- If the file path is correct and the SVG file is correctly exported as a React component, try deleting your project’s
node_modules
directory and runningnpm install
again to reinstall the dependencies. This may fix any issues caused by outdated or corrupted dependencies.
Dynamic import doesn’t work with SVG imported as ReactComponents
If you are using dynamic imports to load SVG files as React components in a create-react-app project and it is not working, there could be a few different issues causing the problem. Here are a few things you can try to fix it:
- Make sure that the SVG files are correctly exported as React components. You can do this by wrapping the contents of the SVG file in a
<svg>
element, and then using theReact.createElement
function to create a new React component. For example:
import * as React from 'react';
function MySvg() {
return (
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
{/* SVG content goes here */}
</svg>
);
}
export default MySvg;
- Make sure that the file paths to the SVG files are correct in your dynamic import statements. If the file paths are incorrect, the imports will fail.
- If the file paths are correct and the SVG files are correctly exported as React components, try deleting your project’s
node_modules
directory and runningnpm install
again to reinstall the dependencies. This may fix any issues caused by outdated or corrupted dependencies.
Failed to compile – Failed to load config “react-app” to extend from
If you are seeing a “Failed to load config ‘react-app’ to extend from” error when trying to compile a create-react-app project, it may be because the react-scripts
package is not installed or is outdated.
To fix this issue, try running the following command in your project’s root directory:
npm install react-scripts
This will install the latest version of react-scripts
, which should resolve the error.
If you are already using the latest version of react-scripts
and are still seeing this error, it may be caused by a problem with your project’s dependencies. In this case, try deleting your project’s node_modules
directory and running npm install
again to reinstall the dependencies.
EACCES: permission denied, open ‘yarn.lock’
It looks like you are encountering a “permission denied” error when trying to open the yarn.lock
file in a create-react-app project. This error is usually caused by incorrect file permissions on the yarn.lock
file.
To fix this issue, you can try changing the permissions on the yarn.lock
file so that you have read and write access. You can do this by running the following command in your project’s root directory:
chmod 644 yarn.lock
This will give you read and write permissions on the yarn.lock
file.
If you are still having issues after changing the permissions on the yarn.lock
file, it may be caused by a problem with your project’s dependencies. In this case, try deleting your project’s node_modules
directory and running npm install
or yarn install
again to reinstall the dependencies.
Use of deprecated webpack DevServer onBeforeSetupMiddleware and onAfterSetupMiddleware options
If you are seeing a warning message about the use of deprecated webpack DevServer
options onBeforeSetupMiddleware
and onAfterSetupMiddleware
in a create-react-app project, it means that these options are no longer supported and should not be used.
To fix this issue, you can try removing any references to these options in your project’s configuration files. If you are not sure where these options are being used, you may need to search your project for references to them.
If you are using a custom version of react-scripts
that includes these options, you may need to update to a newer version that does not include them. You can check the react-scripts
package’s documentation to see which versions are available.
Can’t override ESLint rule “@typescript-eslint/no-unused-vars”
If you are trying to override the @typescript-eslint/no-unused-vars
rule in a create-react-app project and it is not working, there could be a few different issues causing the problem. Here are a few things you can try to fix it:
- Make sure that you are using the correct syntax to override the rule in your project’s
.eslintrc
file. The correct syntax is as follows:
{
"rules": {
"@typescript-eslint/no-unused-vars": ["error", { "vars": "all", "args": "none" }]
}
}
- Make sure that you have the
@typescript-eslint/eslint-plugin
andeslint-config-react-app
packages installed in your project. These packages are required for the@typescript-eslint
rules to work. - If you are using a custom version of
react-scripts
, make sure that it includes the@typescript-eslint/eslint-plugin
package as a dependency. If it does not, you may need to update to a newer version that includes this dependency. - If the issue persists, try deleting your project’s
node_modules
directory and runningnpm install
oryarn install
again to reinstall the dependencies. This may fix any issues caused by outdated or corrupted dependencies.
Create react app won’t work on Windows if there are spaces in your username
It is true that create-react-app may not work properly on Windows if there are spaces in the user’s name. This is because the create-react-app script uses the USERPROFILE
environment variable to create the project, and the variable may not be set correctly if the user’s name includes spaces.
To fix this issue, you can try one of the following solutions:
- Change the user’s name to remove the spaces. This will require creating a new user account with a name that does not include spaces.
- Set the
USERPROFILE
environment variable manually. You can do this by going to the Control Panel, selecting “System and Security,” and then selecting “System.” Click on the “Advanced system settings” link, and then click on the “Environment Variables” button. In the “System variables” section, click the “New” button, and then enter “USERPROFILE” as the variable name and the path to your user folder (e.g., “C:\Users\My User”) as the variable value. - Use a different directory to create the create-react-app project. You can use a directory that does not include spaces in its path to avoid this issue.
Should react-scripts be in dependencies or devDependencies?
In a create-react-app project, the react-scripts
package should be included in the devDependencies
section of your project’s package.json
file.
The devDependencies
section of the package.json
file lists the packages that are required for development and building the project, but are not needed at runtime. This includes tools such as compilers, testing frameworks, and build scripts.
On the other hand, the dependencies
section of the package.json
file lists the packages that are required at runtime for the project to function properly. These are the packages that will be installed in the node_modules
directory and included in the final bundle when the project is built for production.
By including react-scripts
in the devDependencies
section, it will only be installed and used during the development and build process, and will not be included in the final production bundle.
Cannot compile TypeScript app created with CRA because of parsing errors
If you are unable to compile a TypeScript app created with create-react-app because of parsing errors, there could be a few different issues causing the problem. Here are a few things you can try to fix it:
- Make sure that you have the correct TypeScript version installed for your project. Create-react-app projects are configured to use a specific version of TypeScript, and using a different version may cause parsing errors. You can check the version of TypeScript required by your project by looking at the
"typescript"
field in thedevDependencies
section of your project’spackage.json
file. - Make sure that your TypeScript code is correct and follows the correct syntax. TypeScript is a typed superset of JavaScript, and any syntax errors in your code will cause the compiler to throw errors.
- If you are using a custom version of
react-scripts
that includes TypeScript support, make sure that it is properly configured to work with your project. You may need to update thetsconfig.json
file or make other configuration changes to get the compiler to work correctly. - If the issue persists, try deleting your project’s
node_modules
directory and runningnpm install
oryarn install
again to reinstall the dependencies. This may fix any issues caused by outdated or corrupted dependencies.
.env files is not working with CRA 5
The .env
file is a way to define environment variables in a development environment. It should work with Create React App version 5.
If you are having trouble using environment variables with Create React App, here are a few things you can try:
- Make sure that you have a
.env
file in the root of your project. - Make sure that you have correctly defined your environment variables in the
.env
file. The format for defining an environment variable isVARNAME=value
. - Make sure that you are correctly reading the environment variables in your code. In a Create React App project, you can access environment variables using
process.env.VARNAME
. - If you are trying to define environment variables for a production build, you will need to create a
.env.production
file. Environment variables defined in this file will only be available during a production build.
Compilation error with react-scripts 4.0.0 ( Can’t resolve file )
If you are getting a compilation error with react-scripts
, it is likely that there is a problem with your code or your dependencies. Here are a few things you can try to troubleshoot the problem:
- Make sure that all of your dependencies are correctly installed. You can check this by running
npm install
oryarn install
in the root directory of your project. - Check for syntax errors in your code. It is possible that you have a typo or a missing character that is causing the compilation error.
- Make sure that you are using the correct import statements in your code. If you are trying to import a file that does not exist, or if the path to the file is incorrect, you will get a compilation error.
- If you have recently added or removed any dependencies, it is possible that the version of a dependency is incompatible with
react-scripts
. In this case, you may need to update the version of the dependency or roll back to a previous version.
Aliased imports are not supported anymore when creating a new typescript react app
Aliased imports are not supported when creating a new TypeScript React app using Create React App.
Create React App uses a custom Webpack configuration, and it does not support aliased imports. Instead, you can use the paths
field in your tsconfig.json
file to specify custom paths for your imports.
Here is an example of how you can use the paths
field in your tsconfig.json
file to specify a custom path for your imports:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@src/*": ["src/*"]
}
}
}
With this configuration, you can use the following import statement in your code:
import { MyComponent } from '@src/components';
This will be resolved to the following file path:
import { MyComponent } from './src/components';
Bug: [5.0] Can’t resolve ‘react/jsx-runtime’
This error may occur if you are trying to use a version of Create React App that is incompatible with the version of react
that you have installed in your project.
Make sure that you are using the correct version of react
by running the following command in your terminal:
npm list react
This will show you the version of react
that is installed in your project.
Then, check the release notes for the version of Create React App that you are using to see which versions of react
are compatible. You can find the release notes for Create React App here:
https://github.com/facebook/create-react-app/releases
If you find that you are using an incompatible version of react
, you can either upgrade or downgrade your version of react
to a version that is compatible with Create React App.
Add environment variables to manifest.json files
To add environment variables to a Create React App project, you can follow these steps:
- Create a file called
.env
in the root of your project. - In this file, you can define your environment variables. The format for defining a variable is
VARIABLE_NAME=value
. For example:
API_KEY=abcdefghijklmnopqrstuvwxyz
- To access these variables in your code, you can use the
process.env
object. For example:
const apiKey = process.env.API_KEY;
- Create React App will automatically load the environment variables from the
.env
file in development, so you don’t need to do anything else in development. - In production, you will need to build your app with the environment variables included. To do this, you can create a script in your
package.json
file that builds the app with the environment variables. For example:
"scripts": {
"build": "REACT_APP_API_KEY=abcdefghijklmnopqrstuvwxyz react-scripts build"
}
- When you run
npm run build
, Create React App will include the environment variables in the built app.
Keep in mind that the environment variables defined in the .env
file are only available in development, and are not included in the built app. If you want to include environment variables in the built app, you must define them as shown in step 5.
public directory css url
In a Create React App project, the public
directory is where you can store static assets such as images, fonts, and other files that you want to include in your project.
To reference a file in the public
directory from your CSS, you can use the /
prefix. For example:
body {
background-image: url('/background.jpg');
}
This will look for the file background.jpg
in the public
directory.
Keep in mind that the public
directory is the root directory for your built app, so all references to files in the public
directory should use the /
prefix.
Development page blank on first load
If your development page is loading blank on the first load, it could be caused by a number of issues. Here are a few things you can try to troubleshoot the problem:
- Check the JavaScript console for any errors that might be causing the issue. You can open the JavaScript console in your browser by pressing
Ctrl + Shift + J
(Windows) orCommand + Option + J
(Mac). - Make sure that you don’t have any syntax errors in your code. These can cause the development server to fail to start or to crash, which can result in a blank page.
- Check if there are any issues with your dependencies. Try running
npm install
to make sure all of your dependencies are up to date, and then runnpm start
to start the development server. - Check if there are any issues with your environment. Make sure that you have the correct versions of Node.js and npm installed, and that you are running the development server in a supported environment (e.g., not an old version of Internet Explorer).
- If none of these steps help, try deleting the
node_modules
directory and runningnpm install
again to reinstall all of your dependencies.
Error: spawn UNKNOWN
The spawn UNKNOWN
error can occur when the development server fails to start. This can be caused by a number of issues, such as syntax errors in your code or issues with your dependencies.
To troubleshoot this error, you can try the following steps:
- Check the JavaScript console for any errors that might be causing the issue. You can open the JavaScript console in your browser by pressing
Ctrl + Shift + J
(Windows) orCommand + Option + J
(Mac). - Make sure that you don’t have any syntax errors in your code. These can cause the development server to fail to start or to crash, which can result in this error.
- Check if there are any issues with your dependencies. Try running
npm install
to make sure all of your dependencies are up to date, and then runnpm start
to start the development server. - Check if there are any issues with your environment. Make sure that you have the correct versions of Node.js and npm installed, and that you are running the development server in a supported environment (e.g., not an old version of Internet Explorer).
- If none of these steps help, try deleting the
node_modules
directory and runningnpm install
again to reinstall all of your dependencies.
How can I optimize this problem with this build time?
There are several ways you can optimize the build time for a Create React App project:
- Minify your code: You can use a tool like
terser
to minify your JavaScript code, which can reduce the size of your code and make it load faster. - Use code splitting: You can use the
React.lazy
function and theSuspense
component to split your code into smaller chunks that can be loaded on demand. This can help reduce the initial load time of your app. - Use a production build: When you run
npm run build
, Create React App creates a production build of your app. This build is optimized for performance, with minified code and code splitting enabled by default. - Use a CDN: You can use a content delivery network (CDN) to serve your static assets, such as images and fonts. This can help reduce the load time of your app by offloading the delivery of these assets to a separate server.
- Use a performance monitoring tool: You can use a tool like Lighthouse to identify performance issues in your app and suggest ways to fix them.
Add scss import pattern to allow importing all css/scss files from folder
To import all CSS/SCSS files from a folder in a Create React App project, you can use the following pattern:
- Create a
scss
folder in your project and add all of your SCSS files to this folder. - In your JavaScript code, import the SCSS files using the
import
statement and the*
wildcard. For example:
import './scss/*.scss';
This will import all SCSS files in the scss
folder.
Keep in mind that this pattern will not work with CSS files. If you want to import all CSS files from a folder, you will need to import each file individually.
cannot import modules in src aliased in tsconfig paths compilerOptions
If you are having trouble importing modules in a Create React App project that are aliased in the tsconfig.json
file, it could be caused by a few different issues. Here are a few things you can try:
- Make sure that you are using the correct syntax for the import statement. The syntax for an aliased import is
import * as alias from 'module';
, wherealias
is the name of the alias you defined in thetsconfig.json
file, andmodule
is the path to the module. - Check if you have any syntax errors in your
tsconfig.json
file. These can cause the TypeScript compiler to fail and prevent your imports from working. - Make sure that you have the correct version of TypeScript installed in your project. You can check the version of TypeScript that is installed by running the following command:
npm list typescript
- If you are still having trouble, try deleting the
node_modules
directory and runningnpm install
again to reinstall all of your dependencies.
postcss plugins not found when compiling with CRA v5.0.0 and fomantic-ui
If you are using Create React App v5.0.0 and you are getting an error that postcss
plugins are not found when compiling your project with fomantic-ui
, it could be caused by a few different issues. Here are a few things you can try:
- Make sure that you have installed the
postcss
plugins that you are using in your project. You can check thedependencies
section of yourpackage.json
file to see whichpostcss
plugins are installed. If a plugin is not listed, you will need to install it usingnpm install
. - Check if you have any syntax errors in your
postcss.config.js
file. These can cause thepostcss
compiler to fail and prevent your plugins from working. - Make sure that you are using the correct syntax for configuring
postcss
plugins in yourpostcss.config.js
file. The syntax should be:
module.exports = {
plugins: [
require('plugin-name')(options),
],
};
- If you are still having trouble, try deleting the
node_modules
directory and runningnpm install
again to reinstall all of your dependencies.
Add support for node 16 (current release) and scss
To add support for Node.js 16 (the current release) and SCSS to a Create React App project, you can follow these steps:
- Make sure that you have the correct version of Node.js installed. You can check the version of Node.js that is installed by running the following command:
node -v
- If you are using a version of Node.js that is lower than 16, you can upgrade to the latest version by running the following command:
npm install -g n
n latest
- To add support for SCSS, you will need to install the
node-sass
package, which is a library that allows you to use SCSS in your project. You can install this package by running the following command:
npm install node-sass
- Once you have installed
node-sass
, you can use SCSS in your project by importing SCSS files into your JavaScript code. For example:
import './styles.scss';
- If you are using a version of Create React App that is lower than v5.0, you may also need to add the
react-scripts-css-modules
package to your project to enable CSS module support. You can do this by running the following command:
npm install react-scripts-css-modules
yarn pnp doesn’t work with typescript
If you are using Yarn’s Plug’n’Play (PNP) feature and you are having trouble getting it to work with TypeScript in a Create React App project, it could be caused by a few different issues. Here are a few things you can try:
- Make sure that you have the correct version of Yarn installed. You can check the version of Yarn that is installed by running the following command:
yarn -v
- Make sure that you have enabled PNP in your project by creating a
.yarnrc.yml
file in the root of your project with the following content:
usePlugnPlay: true
- If you are using a version of Create React App that is lower than v5.0, you may need to add the
resolutions
field to yourpackage.json
file to ensure that all of your dependencies are compatible with PNP. For example:
{
"resolutions": {
"babel-core": "7.0.0-bridge.0"
}
}
- If you are still having trouble, try deleting the
node_modules
directory and runningyarn
again to reinstall all of your dependencies.
Global .scss declarations (variables etc…) without ejecting
To make global SCSS declarations (such as variables) available to all components in a Create React App project without ejecting, you can follow these steps:
- Create a
scss
folder in your project and add a file called_variables.scss
to this folder. - In this file, you can define your global SCSS variables. For example:
$primary-color: red;
$secondary-color: blue;
- In your JavaScript code, import the
_variables.scss
file at the top of each component that needs access to the global variables. For example:
import './scss/_variables.scss';
- You can then use the global SCSS variables in your component’s styles by referencing them with the
$
symbol. For example:
.my-component {
color: $primary-color;
}
Keep in mind that this approach will only work for global SCSS declarations that do not need to be modified at runtime. If you need to modify SCSS variables based on props or state, you will need to use a different approach, such as the css
prop.
Code coverage comments like `/* istanbul ignore file */` are ignored for jsx files
If you are using a code coverage tool like Istanbul and you are finding that comments like /* istanbul ignore file */
are being ignored for JSX files in a Create React App project, it could be because the code coverage tool is not properly handling the JSX syntax.
One workaround for this issue is to use a .babelrc
file to configure your code coverage tool to ignore JSX files. To do this, you can add the following configuration to your .babelrc
file:
{
"comments": false,
"ignore": [
"*.jsx"
]
}
This will tell the code coverage tool to ignore all JSX files in your project.
Alternatively, you can use the --extensions
option to specify the file extensions that your code coverage tool should ignore. For example:
nyc --extensions .js,.jsx
jest.setTimeout has no effect
If you are using Jest as the test runner for your Create React App project and you are finding that jest.setTimeout
has no effect, it could be because you are trying to set the timeout in a test file rather than in the Jest configuration.
To set the timeout for Jest tests in a Create React App project, you will need to update the jest
configuration in the package.json
file. You can do this by adding a jest
field to the package.json
file with a testTimeout
property, like this:
{
"jest": {
"testTimeout": 10000
}
}
This will set the timeout for all Jest tests to 10 seconds.
Alternatively, you can use the --timeout
option when running Jest to specify the timeout on the command line. For example:
jest --timeout 10000
eslint-config-react-app is not compatible with ESLint 8
If you are using the eslint-config-react-app
configuration for ESLint in a Create React App project and you are getting an error that it is not compatible with ESLint 8, it could be because the eslint-config-react-app
package has not yet been updated to support the latest version of ESLint.
To fix this issue, you can try the following steps:
- Downgrade to a version of ESLint that is supported by
eslint-config-react-app
. You can check thepeerDependencies
field in thepackage.json
file foreslint-config-react-app
to see which versions of ESLint are supported. - Alternatively, you can use a different configuration for ESLint that is compatible with ESLint 8. For example, you can use the
eslint:recommended
configuration by adding the following to your.eslintrc.js
file:
module.exports = {
extends: ['eslint:recommended'],
parserOptions: {
ecmaVersion: 2021,
sourceType: 'module',
ecmaFeatures: {
jsx: true
}
},
env: {
browser: true,
es6: true,
node: true
}
};
No support for web worker when using Typescript and Webpack 5?
If you are using TypeScript and Webpack 5 in a Create React App project and you are having trouble using web workers, it could be because the Create React App build configuration does not include support for web workers by default.
To add support for web workers to a Create React App project, you can try the following steps:
- Install the
worker-loader
package using npm or Yarn:
npm install worker-loader
- Update your Webpack configuration to use the
worker-loader
for web worker files. You can do this by adding the following rule to themodule.rules
array in your Webpack configuration:
{
test: /\.worker\.ts$/,
use: { loader: 'worker-loader' }
}
- Add a
typeRoots
field to yourtsconfig.json
file to include the@types/worker-loader
package:
{
"compilerOptions": {
"typeRoots": ["node_modules/@types", "node_modules/@types/worker-loader"]
}
}
- Import your web worker file in your JavaScript code using the
import
statement:
import Worker from './worker.worker.ts';
can’t create new react app
If you are having trouble creating a new Create React App project, there could be a few different issues causing the problem. Here are a few things you can try:
- Make sure that you have the latest version of Node.js and npm installed on your system. You can check the version of Node.js that is installed by running the following command:
node -v
You can check the version of npm that is installed by running the following command:
npm -v
- Make sure that you are using the correct syntax for the
create-react-app
command. The correct syntax is:
npx create-react-app my-app
Replace my-app
with the name of your project.
- If you are using a version of npm that is lower than 5.2, you may need to install the
create-react-app
package globally before you can use it. You can do this by running the following command:
npm install -g create-react-app
- If you are still having trouble, try deleting the
node_modules
directory and runningnpm install
again to reinstall all of your dependencies.
Stop putting react-app-env.d.ts in src
If you are using Create React App and you want to stop the react-app-env.d.ts
file from being placed in the src
directory, you can do so by adding a skipLibCheck
field to the compilerOptions
section of your tsconfig.json
file. This will tell the TypeScript compiler to skip type checking for declaration files.
Here is an example of how you can configure the tsconfig.json
file to skip type checking for the react-app-env.d.ts
file:
{
"compilerOptions": {
"skipLibCheck": true,
"allowJs": true,
"jsx": "react",
"lib": ["dom", "dom.iterable", "esnext"]
},
"include": ["src"]
}
Keep in mind that this may affect the type checking in your project, so use this option with caution.
Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
If you are using Create React App and you are seeing an error that says “Invalid options object. Dev Server has been initialized using an options object that does not match the API schema,” it could be caused by an issue with the webpack-dev-server
configuration in your project.
Here are a few things you can try to fix this error:
- Make sure that you are using the correct syntax for the
webpack-dev-server
configuration in yourpackage.json
file. The configuration should be an object with aproxy
field that points to your backend server. - Check if you have any syntax errors in your
package.json
file. These can cause thewebpack-dev-server
configuration to fail and trigger the error message. - Make sure that you have the correct version of the
webpack-dev-server
package installed in your project. You can check the version ofwebpack-dev-server
that is installed by running the following command:
npm list webpack-dev-server
- If you are still having trouble, try deleting the
node_modules
directory and runningnpm install
again to reinstall all of your dependencies.
More issues from Facebook repos
Troubleshooting facebook-react | Troubleshooting facebook-jest | Troubleshooting facebook-metro | Troubleshooting facebook-prophet | Troubleshooting facebook-flipper
It’s Really not that Complicated.
You can actually understand what’s going on inside your live applications.