webpack 核心概念 loader

我们直到 webpack 可以打包js css 图片。那么我们来试一下。

改一下index.js 代码,如下。

const Div1 = require("./DivOne.js");
const Div2 = require("./DivTwo.js");
const gz = require("./gz.png");

new Div1();
new Div2();

然后运行命令 npm run bundle 

发现报错:

ERROR in ./src/gz.png 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)

webpack 默认是知道如何打包js 模块的。但是默认它不支持打包图片的。

我们就要去配置webpack。如下,webpack.config.js 。以".png" 结尾的文件,使用 “file-loader” 打包。

const path = require('path');

module.exports = {
  mode: 'production',
  entry: {
    main: './src/index.js'
  },
  module: {
    rules: [{
      test: /\.png$/,
      use: {
        loader: 'file-loader'
      }
    }]
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'bundle')
  }
}

然后得去下载 “file-loader”,使用命令

npm install file-loader --save-dev

好啦。

说到这儿,就可以讲了 Loader 就是一个打包方案。对于一些文件webpack 不知道如何打包处理,这时候使用loader 就可以了。

上面index.js 是CommonJS 语法,下面我们可以用 ES module 语法 来写。

import gz from './gz.png';

var img = new Image();
img.src = gz;

var root = document.getElementById("root");
root.append(img);

 然后打包,就可以在页面上显示出图片了。

猜你喜欢

转载自blog.csdn.net/purple_lumpy/article/details/88375456