What is the nature of Loader how do we write a Loader

Commonly used loader

Babel-loader less-loader ts-loader Why Babel /core is installed when babel-loader is installed and less is installed when less-loader is installed? Install typescript when installing TS-Loader? Because the internal need to introduce the corresponding compiler, take babel-loader source code parsing

Loader nature

Webpack itself can only handle JS, if you want to introduce other things, you need loader; 2. Loader is basically a way to compile things that Webpack doesn’t know.

Workflow of loader

1. Configuration definition; 2. Files of corresponding types are automatically read to Loader. 3. Loader processing; 4. Pack it again to Webpack after processing;

Customize a loader

The directory structure

//index.js
const loaderUtils = require('loader-utils');
const transform = require('./lib/transform')
module.exports = function (resource) {
    console.log(resource);
    const loaderOptions = loaderUtils.getOptions(this) || {};
    letresult = transform(resource); console.log(this); // asyncoperation (null,function(err,result){ callback(null,result,map); }) // the synchronized form this.callback(null,_res,map);return result;
}
Copy the code
//transform.js
module.exports = function(resource){
    let cur = 0;
    let length = resource.length;
    var _result = [];
    var _comArr = [];
    var commandList = [{
        name:'c',
        code:'console.log(value)'
    },{
        name:'a',
        code:'alert(value)'}]; Var tester = {};for(var i=0; i<commandList.length; i++){ tester[commandList[i].name] = function(name){
            return commandList[i].code; }}function _get(st){
        if(commandList.indexOf(st) ! == -1){ _comArr.push({type:'command',
                value:st
            });
        }else if(st === ':'){

        }else if(st === '; '){
            _result.push(_comArr);
            _comArr = [];
        }else if(typeof st === 'string' || typeof st === 'number'){
            _comArr.push({
                type:'value', value:st }); }}while (cur<length){
        _get(resource[cur]);
        cur++;
    }
    function getcode(ast){
        var str = ' ';
        for(var i=0; i<ast.length; i++){ str += tester[ast[i].value](); str = str.replace('value',ast[i][1].value);
            str += '; ';
        }
        return str;
    }
    return getcode(_result);
}
Copy the code