demo__image_loader

demo__image_loader
强烈推介IDEA2021.1.3破解激活,IntelliJ IDEA 注册码,2021.1.3IDEA 激活码  

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说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

 

转载于:https://www.cnblogs.com/heidekeyi/p/10991213.html

本文来源weixin_30595035,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/29764

发表评论