score:0

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.

  1. 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

Related Query

More Query from same tag