Javascript 如何使用es6导入图片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39458511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use es6 import for images
提问by stackjlei
I'm using es6 and want to import an image to use with webpack. Looking at the file-loader doc, this is the example they gave:
我正在使用 es6 并想导入一个图像以与 webpack 一起使用。查看file-loader doc,这是他们提供的示例:
var url = require("file!./file.png");
url will now return something like /static/351f9446b3ba577b6a79e373e074d200.png
url 现在将返回类似 /static/351f9446b3ba577b6a79e373e074d200.png
This works with require, but how do I use import
to do this, I've tried -
这适用于需要,但我如何使用import
它,我试过 -
import * as url from '../images/151.png';
but that doesn't work because url remains undefined. How do I set a variable to what I'm importing when it's an image?
但这不起作用,因为 url 仍未定义。当它是图像时,如何将变量设置为我要导入的内容?
采纳答案by Aleksej Shovgenja
import * as url from '../images/151.png';
but that doesn't work because url remains undefined. How do I set a variable to what I'm importing when it's an image?
从 '../images/151.png' 导入 * 作为 url;
但这不起作用,因为 url 仍未定义。当它是图像时,如何将变量设置为我要导入的内容?
Using Webpack 2.0 with file-loader plugged-in. It works in my case, but import returns something like object bytemap instead of data-uri string;
使用带有文件加载器插件的 Webpack 2.0。它适用于我的情况,但导入返回类似于对象字节图而不是数据 uri 字符串的内容;
And this object has the 'default' property, that contains the same data, as if it was required.
并且这个对象具有“默认”属性,它包含相同的数据,就好像它是必需的一样。
Honestly I'm not sure what is that object, and why there is the default property but that's how I've made it work.
老实说,我不确定那个对象是什么,以及为什么有默认属性,但这就是我让它工作的方式。
import '../css/bootstrap.css';
import '../css/app.scss';
import * as url from '../images/webpack_logo.png';
let img = document.createElement('img');
img.style = {
height: '25%',
width: '25'
};
debugger;
img.src = url.default;
console.log('imported', url);
document.getElementById('img_container').appendChild(img);
The way mentioned in previous answer returned undefined, btw. And it's expected, because that syntax relies on default export to be declared on the source module.
上一个答案中提到的方式返回未定义,顺便说一句。这是预期的,因为该语法依赖于在源模块上声明的默认导出。
回答by Red Mercury
Use
用
import url from "file!./file.png"
import url from "file!./file.png"
回答by Tomek
Using file-loaderyou can achieve this with the nice and simple syntax of:
使用文件加载器,您可以通过以下漂亮而简单的语法实现这一点:
import youNameIt from "../images/151.png";
回答by Aziz
With webpack 4 & es6 I used:
使用 webpack 4 & es6 我使用了:
const url = require('../images/webpack_logo.png');
then used this as the src="url"
in my <img>
tag.
然后src="url"
在我的<img>
标签中使用它。