score:154
I feel like there must be some way to dynamically import all files from a specific directory as their name sans extension, and then use those files as needed.
Not in ES6. The whole point of import
and export
is that dependencies can be determined statically, i.e. without executing code.
But since you are using webpack, have a look at require.context
. You should be able to do the following:
function importAll(r) {
return r.keys().map(r);
}
const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));
score:3
Here is a functional component I made in Reactjs to simply show all the images inside the media
folder in my project (same level as component) using the webpack docs and some of the answers here.
import React from 'react';
const cache = {};
function importAll(r) {
r.keys().forEach((key) => (cache[key] = r(key)));
}
// Note from the docs -> Warning: The arguments passed to require.context must be literals!
importAll(require.context("./media", false, /\.(png|jpe?g|svg)$/));
const images = Object.entries(cache).map(module => module[1].default);
const MediaPage = () => {
return (
<>
<p>Media Page..</p>
{images.map(image => (
<img style={{width: 100}} src={image} />
))}
</>
);
}
export default MediaPage;
With the way that I loaded the images the filenames are lost when mapping from the cache
object but if you need them you can just use the cache
object directly instead as the keys are the filename.
// example with styles just for clarity
return (
<>
<p>Media Page..</p>
{Object.entries(cache).map(module => {
const image = module[1].default;
const name = module[0].replace("./","");
return (
<div style={{float: 'left', padding: 10, margin: 10, border: '2px solid white' }}>
<img style={{width: 100, margin: 'auto', display: 'block'}} src={image} />
<p>{name}</p>
</div>
)
})}
</>
);
score:5
UPDATE It seems like I didnt quite understand the question. @Felix got it right so check his answer. The following code will work in a Nodejs environment only.
Add an index.js
file in the images
folder
const testFolder = './';
const fs = require('fs');
const path = require('path')
const allowedExts = [
'.png' // add any extensions you need
]
const modules = {};
const files = fs.readdirSync(testFolder);
if (files && files.length) {
files
.filter(file => allowedExts.indexOf(path.extname(file)) > -1)
.forEach(file => exports[path.basename(file, path.extname(file))] = require(`./${file}`));
}
module.exports = modules;
This will allow you to import everything from another file and Wepback will parse it and load the required files.
score:10
I have directory of png country flags named like au.png, nl.png etc. So I have:
-svg-country-flags
--png100px
---au.png
---au.png
--index.js
--CountryFlagByCode.js
index.js
const context = require.context('./png100px', true, /.png$/);
const obj = {};
context.keys().forEach((key) => {
const countryCode = key.split('./').pop() // remove the first 2 characters
.substring(0, key.length - 6); // remove the file extension
obj[countryCode] = context(key);
});
export default obj;
I read a file like this:
CountryFlagByCode.js
import React from 'react';
import countryFlags from './index';
const CountryFlagByCode = (countryCode) => {
return (
<div>
<img src={countryFlags[countryCode.toLowerCase()]} alt="country_flag" />
</div>
);
};
export default CountryFlagByCode;
score:12
It's easy. You can use require
(a static method, import is just for dynamic files) inside the render
. Like the example below:
render() {
const {
someProp,
} = this.props
const graphImage = require('./graph-' + anyVariable + '.png')
const tableImage = require('./table-' + anyVariable2 + '.png')
return (
<img src={graphImage}/>
)
}
score:13
A functional approach to solve this problem:
const importAll = require =>
require.keys().reduce((acc, next) => {
acc[next.replace("./", "")] = require(next);
return acc;
}, {});
const images = importAll(
require.context("./image", false, /\.(png|jpe?g|svg)$/)
);
Source: stackoverflow.com
Related Query
- Dynamically import images from a directory using webpack
- I am getting a void returned when trying to dynamically import images from a directory using webpack
- how to import LESS files from specific path using webpack less-loader?
- Using require('...') to dynamically import images in react js not working anymore
- Using components from an external directory in a Electron project with Webpack
- How to import css from node_modules using webpack 2
- Webpack import React component from directory
- How to display image from src/images without using import at the top and without using public directory in react/reactjs
- Dynamically Add Images React Webpack
- Display images in React using JSX without import
- using css modules, how can I import classes from a file
- How import object from external JS file in React JS using web pack
- How to import all images from a folder in ReactJS?
- import CSS and JS files using Webpack
- how does webpack import from external url
- CDN links for React packages and how to import it when using react using the scripts from CDN
- How do I dynamically import images in React?
- React import from parent directory
- Heroku "content not from webpack is served from /app/public" despite using all default create-react-app config
- How to import images from JSON data into create-react-app
- How to import everything from a module in react using es6?
- Using webpack to load CSS files from node modules
- Nextjs import external components from parent directory
- bundle.js missing from webpack build when using webpack-dev-server
- Using Webpack alias cause to ESLint error on import alias in WebStorm
- Remove .html extension from a url for a website built using React and Webpack
- Webpack - Require Images Using File-Loader
- How to use images from sharp module in React and Webpack project
- Make all images file point to CDN using Webpack
- Can't load images using webpack dev server middleware
More Query from same tag
- React Login with Redirect on callback
- Trying to connect React and Java resulted in browser showing a blank page
- Is there a way to get the position of the curson inside a text field using Javascript?
- Semantic UI React Modal : Portal.render(): A valid React element (or null) must be returned
- React - renderSubtreeIntoContainer: Use case example
- How to use client.query without JSX components in Apollo Client?
- Navigate to a section of another page in MUI 5
- window.scrollTo() is not functioning properly in react ionic
- How to pass JSON to Redux -> React Component
- Functional React Component with an argument in curly braces
- Return from an IF statement inside of a react render function
- How to test action props from ReactiveDict inside React component with Enzyme
- React-hook-form with react-select formState not valid but controller don't giving an error
- TypeError: Ajv is not a constructor when I run npm run build
- React CSS Modules - Apply style to child each tag
- React testing - mock function
- How to add a key to the table
- cache.addAll cannot cache file exept .html
- How do I use sinon on a bound React component method?
- How to forbid children for a React component with typescript?
- What is the best method to change React State based off of State?
- Svg animations not running on Safari
- Get an element created by a script in react without ref
- Does Immer allow us to store class instances in a redux reducer?
- How to change font size on button click?
- componentDidMount() returns an undefined value
- Dynamic Routes: React/TypeScript
- Creating a JSX list in React with an object
- Using css bootstrap only for accordian
- How to set the scroll-thumb at the centre of the scrollbar