-
Notifications
You must be signed in to change notification settings - Fork 93
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Dynamically import svgs #51
Comments
@mick-feller Have you tried the dynamic import syntax? https://reactjs.org/docs/code-splitting.html#import? This is untested, but I think it should look something like this: const reqSvgs = require.context('./svgdir', true, /\.svg$/);
reqSvgs.keys().map((filename) => {
import(`./svgdir/${filename}`)
.then(Icon =>
<div key={filename} className="icon">
<Icon />
</div>
)
.catch(/* fallback */)
}) |
@chancestrickland - How would you use each specific Icon in JSX when implementing your method? Doing
|
This does not work: let Foo;
// I've placed a single svg file in the folder
const reqSvgs = require.context('./icons', true, /\.svg$/);
reqSvgs.keys().map((filename) => {
filename = filename.replace('./','')
let name = filename.replace(/\.[^.]*$/,'')
import(`./icons/${filename}`)
.then(Icon => {
Foo = () => <Icon />;
})
})
const Icon = ({type}) => {
return <Foo/> // assume this will be dynamic using "type"
}
export default Icon ERROR:
|
I now understand |
This will give you |
@yairEO @mick-feller did you ever fix this? I'm trying to import inline:
Which returns the module. Webpack config:
And running version |
@jp1987 we actually moved away from this plugin and went with @svgr/webpack, the webpack piece is what we setup in storybook, but you can obviously convert this to regular webpack. config.module.rules.push({
test: /\.svg?$/,
oneOf: [
{
use: [
{
loader: '@svgr/webpack',
options: {
prettier: false,
svgo: true,
svgoConfig: {
removeViewBox: false
},
titleProp: true,
},
},
]
}
]
}) And then in our code we actually do this to generate an object of all our SVG's in a folder: const getSVGS = () => {
const context = require.context('../../icons', true, /\.svg$/);
const obj = {};
context.keys().forEach((key) => {
obj[key] = context(key).default;
});
return obj;
}; |
So we have a library with all our svg icons in it.
I'm looking for a way to import all these svgs dynamically and display them in our styleguide (storybook) to give a visual representation of which icons we have.
I was trying something like this but no luck:
But no luck, anyone any idea how i can make this work?
The text was updated successfully, but these errors were encountered: