zoukankan      html  css  js  c++  java
  • webpack之理解loader

    我们在写webpack配置文件的时候,应该有注意到经常用到loader这个配置项,那么loader是用来做什么的呢?
    loader其实是用来将源文件经过转化处理之后再输出新文件。
    如果是数组形式的话,它的执行顺序是相反的,最后一个loader最早被调用,下一个loader传入的是上一个loader的返回结果。

    基础的loader文件

    首先在webpack.config.js里调用新建的loader文件

    const path = require('path');
    module.exports = {
        module: {
            rules: [
                {
                    test: /.js$/,
                    exclude: /node_modules/,
                    use: {
                        loader: path.resolve('./loader/index.js'),
                        options: {}
                    }
                }
            ]
        }
    }
    

    代码在传入loader文件的时候已经被转为string了,loader文件最终也必须返回string数据。loader文件里代码如下:

    module.exports = function (content) {
        console.log('loader文件', content);
        return content;
    }
    

    获取options配置数据

    webpack.config.js文件里,在配置loader的同时,还可以配置options。

    const path = require('path');
    module.exports = {
        module: {
            rules: [
                {
                    test: /.js$/,
                    exclude: /node_modules/,
                    use: {
                        loader: path.resolve('./loader/index.js'),
                        options: {
    						data: ’自定义的配置'
    					}
                    }
                }
            ]
        }
    }
    

    在loader文件里面可以利用webpack提供的loader-utils来获取options。

    const loaderUtils = require('loader-utils');
    module.exports = function (content) {
        // this是loader函数的执行上下文
        const options = loaderUtils.getOptions(this);
        console.log('配置文件', options); // {data:'自定义的配置'}
        return content;
    }
    

    异步loader

    之前举的例子都是在同步的情况下,那么在异步的情况中,必须调用this.async()来告知loader等待异步结果,它会返回this.callback()回调函数,这时候loader必须返回undefined

    module.exports = function(content) {
      const callback = this.async();
      someAsyncOperation(content, function(err, result) {
        if (err) return callback(err);
        callback(null, result, map, meta);
      });
    };
    

    总结

    开头就提到过了,loader实质上是用来处理源文件的,在loader函数里面一般都会对代码进行转化处理,这里就会用到AST,将代码转换为AST方便对代码进行处理。

  • 相关阅读:
    Jackson学习资料
    servlet/filter/listener/interceptor区别与联系
    JDBC、JTA、Spring的事务管理
    hibernate 的SessionFactory的getCurrentSession 与 openSession() 的区别
    Spring MVC如何配置OpenSessionInViewInterceptor并结合Hibernate使用
    SpringMVC中使用Interceptor拦截器
    Hibernate条件查询
    Spring MVC之@RequestBody, @ResponseBody 详解
    Sping Environment为Null的原因和解决方法
    SpringMVC+Thymeleaf如何处理URL中的动态查询参数
  • 原文地址:https://www.cnblogs.com/minz/p/10651965.html
Copyright © 2011-2022 走看看