score:17

Accepted answer

looks like its purpose is to import named exports from non js/css assets. currently, within the cra, it appears to only be implemented for svg assets. the goal is to offer another way to import svgs as react components versus the standard import as a url that needs to be applied to an img element.

without plugin (default import)

import * as react from 'react';
import logo from './logo.png'; // import file as a url

function header() {
  return <img src={logo} alt="logo" />;
}

export default header;

with plugin (named import)

import * as react from 'react';
import { reactcomponent as logo } from './logo.svg'; // import file as a react component

function header() {
  return <logo />;
}

export default header;

update

going deeper, it appears that the plugin aids in importing svg files in the following ways:

import logo from "logo.svg"; // default import
import { logourl } from "logo.svg"; // named import
import { reactcomponent as logo } from "@svgr/webpack?-svgo!logo.svg"; // reactcomponent import

the cra specifically targets svg file formats as shown in their test suites. as to whether or not it supports other non-js files, not likely (especially since the babel plugin is only utilized once in the cra webpack config).

as mentioned in the svgr docs:

svgr can be used as a webpack loader, this way you can import your svg directly as a react component.

this particular plugin aims to import any svg file as the default export.

please note that by default, @svgr/webpack will try to export the react component via default export if there is no other loader handling svg files with default export.

whereas the cra appears to utilize file/url loader for the default/named exports and specifically maps a reactcomponent named export to the svgr webpack plugin.


Related Query

More Query from same tag