demo__image_loader

Posted heidekeyi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了demo__image_loader相关的知识,希望对你有一定的参考价值。

环境

webpack4.x

文件结构

│  package.json
│  webpack.config.js
│  yarn.lock
│
├─dist 
│      1f871aa58.png
│      bundle.js
│      index.html
│
├─node_modules
└─src
    ├─img
    │      1.png
    │
    └─js
            app.js

文件内容(app.js)

//创建img标签,并使用引入的图片文件
let src = require(‘../img/1.png‘);
let img = new Image();
img.src = src;
img = document.querySelector("body").appendChild(img);

 

方法1:file-loader

package.json

  "name": "file",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": 
    "file-loader": "^4.0.0",
    "webpack": "^4.33.0",
    "webpack-cli": "^3.3.3"
  


webpack.config.js
const path = require(‘path‘);

module.exports = 
    entry: 
        app: ‘./src/js/app.js‘
    ,
    output: 
        filename: ‘bundle.js‘,
        path: path.join(path.resolve(__dirname), ‘dist‘)
    ,
    mode: ‘development‘,
    module: 
        rules: [
            test: /\.(jpg|png|gif)$/,
            use: 
                loader: ‘file-loader‘,
                options: 
                    name: ‘[name][hash:8].[ext]‘
                
            
        ]
    
;

 

方法2:url-loader(生成文件的话需要file-loader)

package.json

  "name": "file",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": 
    "file-loader": "^4.0.0",
    "url-loader": "^2.0.0",
    "webpack": "^4.33.0",
    "webpack-cli": "^3.3.3"
  

 

webpack.config.js
const path = require(‘path‘);

module.exports =
entry:
app: ‘./src/js/app.js‘
,
output:
filename: ‘bundle.js‘,
path: path.join(path.resolve(__dirname), ‘dist‘)
,
mode: ‘development‘,
module:
rules: [

test: /\.(jpg|png|gif)$/,
use :
loader : ‘url-loader‘,
options :
limit : 2 * 1024,
name: ‘[name][hash:8].[ext]‘


]

;

 

打包(打开index.html可以看见图片)

npx webpack

 

以上是关于demo__image_loader的主要内容,如果未能解决你的问题,请参考以下文章

VSCode 配置 用户自定义代码片段 自定义自动代码补充

[AndroidStudio]_[初级]_[配置自动完成的代码片段]

[AndroidStudio]_[初级]_[配置自动完成的代码片段]

这些 C++ 代码片段有啥作用?

CIFAR-10 DEMO代码阅读与理解

带你轻松解密白盒测试(Demo详解)