Skip to content
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

Require a image in CSS #45

Open
cwtuan opened this issue Nov 16, 2015 · 5 comments
Open

Require a image in CSS #45

cwtuan opened this issue Nov 16, 2015 · 5 comments

Comments

@cwtuan
Copy link

cwtuan commented Nov 16, 2015

I can require a image in JS easily like:

var img = document.createElement('img');
img.src = require('./glyph.png');

How can I require a image in CSS? I need something like:

.H1:before {
  content: url({require('./glyph.png)});
}

@nkbt
Copy link

nkbt commented Nov 16, 2015

just

content: url("./glyph.png");

You will need to use url-loader, webpack will do all the rest.

See https://github.com/nkbt/esnext-quickstart/blob/master/webpack.config.js#L19-L24 for example

@ankitduseja
Copy link

Thanks! This is probably the best how-to guide out there.

@sibelius
Copy link

sibelius commented Aug 1, 2016

@nkbt is this the same for a img src?

because this line: https://github.com/Lar21/webpack-starter-angular/blob/master/src/components/home/home.html#L7

is not working

@nkbt
Copy link

nkbt commented Aug 1, 2016

@sibelius webpack does not process html files and <img> sources won't work.
Id you use React, you do <img src={require('../../img.jpg')} />, if you use some templating language you will need to pass JS variable like:

const imgSrc = require('../../img.jpg');

// ....

// some kind of template
render(`
  <img src="%imgSrc%" />
`)

in angular you would use scope/this

$scope.imgSrc = require('../../img.jpg');

//....

// template.html
<img="imgSrc" />

And so on.

Just remember, that webpack simply returns string from require statement with files/images with correct path to automatically generated file, so you are then free to use it in any way your templating allows you.

@sibelius
Copy link

sibelius commented Aug 2, 2016

@nkbt thanks, this works great! \o/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants