webpack4.29.x成神之路(二十) 编写一个loader

栏目: JavaScript · 发布时间: 7年前

内容简介:上节:css代码分割目录:

目录

上节:css代码分割

目录:

webpack4.29.x成神之路(二十) 编写一个loader

先改一下src/index.js:

import _ from 'lodash';
const root = document.getElementById('root');
root.innerText = _.join(['hello', 'webpack'], '-');

现在写一个简单的loader,将所有的webpack替换成其它内容,内容可通过options配置。

在根目录新建loaders/replace-loader.js。

loaders/replace-loader.js:

const { getOptions } = require('loader-utils');
module.exports = function(source) {
  /* 
    this指向webpack
    source:打包后的文件内容
    this.query options参数
  */
 const options = getOptions(this) || {};

 // 返回处理后的结果,相当于是打包拦截器
 return source.replace('webpack', options.name || 'Madao');
}

source是打包后生成的文件,options可以拿到配置参数,这个loader会将所有webpack替换成options.name的内容,如果没指定options.name, 就替换成Madao.

然后引用这个loader, 修改webpack/webpack.base.js:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const { resolve } = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: resolve(__dirname, '../bundles')
  },

  // 注册loader
  resolveLoader: {
    // loader查找顺序,从左到右
    modules: ['node_modules', './loaders/']
  },

  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      
      // 先不传options
      use: ['replace-loader', 'babel-loader']
    }, {
      test: /\.(gif|jpg|jpeg|png|svg)$/,
      use: ['url-loader']
    }]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html'
    })
  ]
};

安装loader工具库:npm i loader-utils -D

然后npm run build, 打开bundles下的main.[contenthash].js文件,应该可以搜索到Madao:

webpack4.29.x成神之路(二十) 编写一个loader

然后我们自己传一个配置参数,修改webpack/webpack.base.js:

// 省略
module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      use: [{
        loader: 'replace-loader',
        options: {
          name: '史珍香'
        }
      }, 'babel-loader']
    }, {
      test: /\.(gif|jpg|jpeg|png|svg)$/,
      use: ['url-loader']
    }]
  },
// 省略

再次npm run build,可以看到webpack就换成了'史珍香':

webpack4.29.x成神之路(二十) 编写一个loader

一个简单的loader就实现了

下节:编写一个plugin


以上所述就是小编给大家介绍的《webpack4.29.x成神之路(二十) 编写一个loader》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Natural Language Processing with Python

Natural Language Processing with Python

Steven Bird、Ewan Klein、Edward Loper / O'Reilly Media / 2009-7-10 / USD 44.99

This book offers a highly accessible introduction to Natural Language Processing, the field that underpins a variety of language technologies, ranging from predictive text and email filtering to autom......一起来看看 《Natural Language Processing with Python》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具