Root Imports with Create React App
This is a simple step by step tutorial on how to bring “root imports” or “absolute imports” to Create React App without having to eject.
Step 1
We need to setup react-app-rewired
which allows us to tinker with the Webpack config the create-react-app
generates.
npm install react-app-rewired --save-dev
After installing the NPM package, you need to change the scripts in your package.json
file
/* package.json */
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom"
}
Step 2
We need to install the Babel plugin which will help us with the absolute paths.
npm install babel-plugin-root-import --save-dev
You can find more documentation on this plugin here: https://github.com/entwicklerstube/babel-plugin-root-import
Step 3
The last step is to connect everything together. In the root of your create-react-app
project you need to create a file named config-overrides.js
with the following content
/* config-overrides.js */const { injectBabelPlugin } = require('react-app-rewired');const rootImport = ['root-import', {
rootPathPrefix: '~',
rootPathSuffix: 'src',
}];module.exports = function override(config, env) {
config = injectBabelPlugin(rootImport, config); return config;
}
That’s it!
Now you can replace import Button from '../../../ui/generic/Button'
with import Button from '~/components/ui/generic/Button'
.