In order to deal with this situation, we can use some third-party components.
The first library is the babel-plugin-root-import, which allows us to import components using root-based paths.
Install
npm install babel-plugin-root-import --save-dev
Custom root
const rootImportOpts = {
root: __dirname,
rootPathPrefix: '~/',
rootPathSuffix: 'src/js',
};
module.exports = {
plugins: [['babel-plugin-root-import', rootImportOpts]],
};
babel.config.js
const rootImportOpts = {
root: __dirname,
rootPathPrefix: '~/',
rootPathSuffix: 'src/Assets',
};
module.exports = (api) => {
api.cache(true);
const plugins = [['babel-plugin-root-import', rootImportOpts]];
return { plugins };
};
now you can use like this:
<img src={require(`~/your-image-name`)} alt=""/>
for more information you can visit babel-plugin-root-import github.
- This second we need to install is the react-app-rewired. This component allow us to change webpack configuration without using ‘eject’ and without creating a fork of the react-scripts