Parcel: can't dynamic require images

Created on 5 Jul 2018  路  11Comments  路  Source: parcel-bundler/parcel

馃悰 bug report


I use parcel to package the react project,but can't dynamic require images

File Directory
image

馃帥 Configuration (.babelrc, package.json, cli command)


.babelrc

{
  "presets": [
    "env",
    "react"
  ],
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "style": true
      }
    ],
    [
      "transform-runtime",
      {
        "polyfill": false,
        "regenerator": true
      }
    ]
  ]
}

package.json

{
  "name": "parcelReactDemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "parcel ./src/index.html",
    "build": "parcel build ./src/index.html -d build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "antd": "^3.1.4",
    "react": "^16.2.0",
    "react-dom": "^16.2.0"
  },
  "devDependencies": {
    "babel-plugin-import": "^1.6.3",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "less": "^2.7.3",
    "parcel-bundler": "^1.9.4"
  }
}

馃 Expected Behavior

Each picture should be properly introduced

馃槸 Current Behavior

image

馃拋 Possible Solution

馃敠 Context

馃捇 Code Sample

app.js

import React, { Component } from 'react'

export default class App extends Component {

    render () {
        return (
            <div>
                {[1, 2, 3].map(
                    item => <img key={item} src={require(`./${item}.png`)}
                                 alt=""/>)}
            </div>
        )
    }
}

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './containers/app.js'

ReactDOM.render(<App/>, document.getElementById('root'))

馃實 Your Environment

| Software | Version(s) |
| ---------------- | ---------- |
| Parcel | 1.9.4
| Node | 8.9.3
| npm/Yarn | npm 5.5.1
| Operating System | win10

Most helpful comment

Well you didn't apply my code snippet at all?

I'll write an example :)

import React, { Component } from 'react';

/*
Images should resolve to the following:
{
  '1': '/1-hash.png',
  '2': '/2-hash.png',
  '3': '/3-hash.png'
}
*/
import images from './*.png';

export default class App extends Component {

    render () {
        return (
            <div>
                {Object.keys(images).map(
                    key => {
                        return <img key={key} src={images[key]}
                                    alt=""/>
                    })}
            </div>
        )
    }
}

All 11 comments

Probably better to use something like this:

const images = require('./images/*.png');

// images returns an object with all the paths of the images matching the glob with content hashing this also helps with improving your caching
// You can loop through images :)

@DeMoorJasper
It still doesn't work properly
error message: Uncaught Error: Cannot find module './1.png'

import React, { Component } from 'react'

export default class App extends Component {

    render () {
        return (
            <div>
                {[1, 2, 3].map(
                    item => {
                        const images = require(`./${item}.png`)
                        return <img key={item} src={images}
                                    alt=""/>
                    })}
            </div>
        )
    }
}

Well you didn't apply my code snippet at all?

I'll write an example :)

import React, { Component } from 'react';

/*
Images should resolve to the following:
{
  '1': '/1-hash.png',
  '2': '/2-hash.png',
  '3': '/3-hash.png'
}
*/
import images from './*.png';

export default class App extends Component {

    render () {
        return (
            <div>
                {Object.keys(images).map(
                    key => {
                        return <img key={key} src={images[key]}
                                    alt=""/>
                    })}
            </div>
        )
    }
}

@DeMoorJasper Hello, excuse me, if there is a Vue file, is there a way to achieve this? Introduce static resources in the data.

@QAQLiuCong parcel works the same in any asset type, so as long as you can pass a link to the vue component it should work

Sent with GitHawk

@DeMoorJasper OK,Thank you for your reply

Closing this, as I'm pretty sure it's resolved by my response

How can I force application to refresh folder to look images like in your example
'''
import images from './*.png';
'''
eg. after I completed upload file to folder ?

@DeMoorJasper but this solution is very limited, as you are not having the hash. Is it somehow possible to get the full name of the file?

Thanks you @DeMoorJasper. Goddamn I spent like an hour trying to figure this out, and @bologer if you know the file name you can just call images[FILENAME]

Is there any way to make this work with Parcel 2 (currently trying with 2.0.0-alpha.3.2)? I've attempted variations of require('./images/*.png'), require('url:./images/*.png'), require('url:~/src/images/*.png') etc. all to no avail, but I can't see anything that looks like it's related to this in the issues or milestones. Is there a trick I'm missing?

Was this page helpful?
0 / 5 - 0 ratings