Loading...

编写第一个webpackloader

编写一个webpack loader,loader的作用是获取你写的源代码,根据自己的操作对源代码的字符进行自定义的处理,相当于解释器、翻译器.

1、在入口文件(webpack.config.js中的entry配置的js文件)中写如下代码

console.log('hello,vue');

2、接下来编写一个loader,将console.log中的vue替换成react,项目根目录下新建loaders文件夹,新建customLoader.js文件,内容如下

module.exports = function (source) {
    return source.replace(this.query.name, 'react')    //这个this.query是webpack配置的loader option中的变量,这里是vue;source指的是源代码.
}

3、项目根目录下新建webpack.config.js

const path = require('path')
module.exports = {
    mode: 'development',
    entry: {
        main: './src/index.js'
    },
    resolveLoader: {
        modules: ['node_modules', 'loaders']   //指的是在node_modules、loaders中查找loader,loaders是自己配置的,可以自行修改
    },
    module: {
        rules: [
            {
                test: /\.js/,
                use: [
                    {
                        // loader: path.resolve(__dirname, './loaders/customLoader.js'),   //没使用resolveLoader就需要使用path路径
                        loader: 'customLoader',
                        options: {
                            name: 'vue'   
                        }
                    }
                ]
            }
        ]
    },
    output: {
        filename: '[name].[contenthash].js',
        path: path.resolve(__dirname, 'dist')
    }
}

4、打包,修改成功

扩展:如果想要在loader中使用异步操作,需要使用async

4-1、customLoader.js 配置如下

module.exports = function (source) {
    const callback = this.async();   //返回一个this.callback
    setTimeout(() => {
        let result = source.replace(this.query.name, 'react');
        callback(null,result)   //第一个参数是报错信息,第二个是处理后的源码
    }, 5000);
}

  

原文链接:https://www.cnblogs.com/uimeigui/p/14097925.html
本文来源 爱码网,其版权均为 原网址 所有 与本站无关,文章内容系作者个人观点,不代表 本站 对观点赞同或支持。如需转载,请注明文章来源。

© 版权声明

相关文章