如何写webpack loader帮助你升职加薪

简单来说loader是让其他类型的文件转换成webpack能理解的js代码的一段代码(函数)

Out of the box, webpack only understands JavaScript files. Loaders allow webpack to process other types of files and converting them into valid modules that can be consumed by your application and added to the dependency graph.、

在你的应用程序中,有三种使用 loader 的方式:
  • 配置(推荐):在 webpack.config.js 文件中指定 loader。
  • 内联:在每个 import 语句中显式指定 loader。
  • CLI:在 shell 命令中指定它们。

配置

module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          }
        ]
      }
    ]
  }

内联

import Styles from 'style-loader!css-loader?modules!./styles.css';

选项可以传递查询参数,例如 ?key=value&foo=bar,或者一个 JSON 对象,例如 ?{"key":"value","foo":"bar"}。

CLI

webpack --module-bind jade-loader --module-bind 'css=style-loader!css-loader'
会对 .jade 文件使用 jade-loader,对 .css 文件使用 style-loader 和 css-loader。
那么如何编写一个webpack-loader呢? 官方指南,下面就带你一起手写一个webpack-loader?
需求如下:
我们要写一个对txt文件中的[name]替换成17,非常简单.如下:
//src/loader.js
const {getOptions} = require('loader-utils')

module.exports = function (source){
    const options = getOptions(this);
    console.log(source);
    source = source.replace(/\[name\]/g, options.name);
    console.log(source);
    return `export default ${JSON.stringify(source)}`
}

//webpack.config.js配置

const path = require('path')

module.exports = {
    mode:'development',
    context: __dirname,
    entry: `./src/test.txt`,
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.txt'
    },
    module: {
        rules: [
            {
                test: /\.txt$/,
                use: [
                    {
                        loader: path.resolve(__dirname, './src/bar-loader.js'),
                        options: {
                            name: '18hahaha'
                        }
                    },
                    {
                        loader: path.resolve(__dirname, './src/loader.js'),
                        options: {
                            name: '17'
                        }
                    }
                ]
            }
        ]
    }
}
 

那么如何编写一个loader与现有的loader一起使用呢?

接着写:
//src/bar-loader.js

const { getOptions } = require('loader-utils')

module.exports = function (source) {
    const options = getOptions(this);
    console.log(11111,source);
    source = source.replace(/17/g, options.name);
    console.log(11111, source);
    return `export default ${JSON.stringify(source)}`
}

//webpack.config.js
rules: [
            {
                test: /\.txt$/,
                use: [
                    {
                        loader: path.resolve(__dirname, './src/bar-loader.js'),
                        options: {
                            name: '18hahaha'
                        }
                    },
                    {
                        loader: path.resolve(__dirname, './src/loader.js'),
                        options: {
                            name: '17'
                        }
                    }
                ]
            }
        ]

还可以使用异步模式(async mode)
调用 this.async()来获取this.callback()方法,然后在异步调用的回调函数中通过callback返回null以及处理结果。
module.exports = function(content) {
    var callback = this.async();
    if(!callback) return someSyncOperation(content);
    someAsyncOperation(content, function(err, result) {
        if(err) return callback(err);
        callback(null, result);
    });
};
那么如何编写一个loader的单元测试呢?OK.直接上代码
编写一个compiler.js
import path from 'path'
import webpack from 'webpack'
import memoryfs from 'memory-fs'

export default (fixture, options = {}) => {
    const compiler = webpack({
        context: __dirname,
        entry: `./${fixture}`,
        output: {
            path: path.resolve(__dirname),
            filename: 'bundle.js'
        },
        module:{
            rules:[
                {
                    test: /\.txt$/,
                    use: {
                        loader: path.resolve(__dirname, '../loaders/loader.js'),
                        options: {
                            name: '17'
                        }
                    }
                }
            ]
        }
    })

    compiler.outputFileSystem = new memoryfs();
    return new Promise((resolve, reject) => {
        compiler.run((err, stats) => {
            if(err) reject(err)
            resolve(stats)
        })
    })
}
这样就可以测试了
import compiler from './compiler.js';

test('Inserts name and outputs JavaScript', async () => {
    const stats = await compiler('example.txt');
    // console.log(stats.toJson());

    const output = stats.toJson().modules[0].source;

    expect(output).toBe(`export default "Hey 17!\\n"`);
});

好了,demo写完了,剩下就是根据需求编写了.
最后奉上 loader API、官网的 loaders.

如果觉得文章不错,可以给小编发个红包给予鼓励.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值