• 教你开发一个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.

     

      

     

      

      

  • 相关阅读:
    课堂讨论电子版
    项目目标文档
    系统利益相关者
    实训八(游戏背景)
    实训七(项目准备与创建)
    实训六(Cocos2dx游戏分享到微信朋友圈----AppID的获取)
    实训五(Cocos2dx-3.x 打包apk再理解)
    实训四(cocos2dx sharesdk集成-1)
    实训三(cocos2dx 3.x 打包apk)
    实训二(cocos2dx 2.x 打包apk)
  • 原文地址:https://www.cnblogs.com/yiyi17/p/12161617.html
Copyright © 2020-2023  润新知