demo__image_loader

surroundings

webpack4.x

File Structure

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

File contents (app.js)

// create the img tag, and introduced the use of image files 
the let src = The require ( '../ img / 1.png' ); 
the let img = new new Image (); 
img.src = src; 
img = document.querySelector ( " . body ") appendChild (img) ;

 

Method 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]'
                }
            }
        }]
    }
};

 

Method 2: url-loader (generated file, if desired, 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]'
}
}
}]
}
};

 

Packaging (open index.html can see the picture)

npx webpack

 

Guess you like

Origin www.cnblogs.com/heidekeyi/p/10991213.html