zoukankan      html  css  js  c++  java
  • 教你开发一个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.

     

      

     

      

      

  • 相关阅读:
    招聘测试开发二三事
    首次曝光:大厂都是这样过1024的,看的我酸了
    1024程序员节:今天,我们不加班!
    TesterHome创始人思寒:如何从手工测试进阶自动化测试?十余年经验分享
    ASP.NET网站中设置404自定义错误页面
    IIS 7 应用程序池自动回收关闭的解决方案
    ASP.NET项目中引用全局dll
    ASP.NET WebForm中前台代码如何绑定后台变量
    Git使用过程中出现项目文件无法签入Source Control的情况
    ASP.NET中身份验证的三种方法
  • 原文地址:https://www.cnblogs.com/yiyi17/p/12161617.html
Copyright © 2011-2022 走看看