-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Import all files in folder #705
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
Comments
This seems like a good question for StackOverflow webpack/es6. That said, you probably want require.context. |
@emmanuelmillionaer Couple of ways: Using dynamic import, where you can simply require these images inline and it will work. For ex: <img src={`${require('../static/images/foo.png')}`} /> OR, create an index.js file inside export * from 'user.png'
export * from 'team.jpg' and it would allow you to do: import { user, team } from 'static/images' OR, create a JS helper to do this as well: const images = require.context('../images/static', true)
const imagePath = (name) => images(name, true)
// then within your component
console.log(imagePath('./user.png')) // it's relative to context |
@rossta Thank you very much, |
So without importing the images we can't use the images from rails view? Is there anyway to tell webpacker to compiles assets from specified folder without importing them in the pack files, like sprocket used to compile all assets from app/assets folder? |
@aruprakshit I had a hard time figuring out the details too so I though I'd share here for you and others. To use all images in a "webpacker" folder - say
then use them in your Rails view like this, for example in
or
Note the |
As discussed in rails#705, the documentation is missing the essential addition of require.context in your app js to make the `asset_pack_path` and `image_pack_tag`
@klausbadelt Can I use |
Is there a JS equivalent of this for loading all JS files in a directory in to |
@AlecRust Yes there is. https://webpack.js.org/guides/dependency-management/#context-module-api const importAll = (r) => r.keys().forEach(r);
importAll(require.context('../src/', true, /\.js$/)); |
const importViewScripts = (page) => page.keys().forEach(page);
document.addEventListener("turbolinks:load", () => {
importViewScripts(require.context("../src/", true, /\.js$/));
}); |
Uh oh!
There was an error while loading. Please reload this page.
Hi, thanks for this great gem: 💯
Instead of writing e.g. in "javascript/packs/application.js":
What's the best option to require all files in the
images/static
folder? Thanks 🙂The text was updated successfully, but these errors were encountered: