边界: loader 本质是一个函数,它的作用是将某个源码字符串转换成另一个源码字符串返回

webpack做的事情,仅仅是分析出各种模块之间的依赖关系,然后形成资源列表,最终打包指定的文件中

更多的功能需要借助webpack loader和webpack plugins完成

image.png

loader函数将在模块解析的过程中被调用,已得到最终的源码

全流程

image.png

chunk中解析模块的流程

image.png

chunk中解析模块的更详细的流程

2020-01-13-09-35-44.png

处理loaders流程

2020-01-13-10-29-54.png
loader配置:

完整配置

  1. module.exports = {
  2. module: { //针对模块的配置,目前版本只有两个配置,rules、noParse
  3. rules: [ //模块匹配规则,可以存在多个规则
  4. { //每个规则是一个对象
  5. test: /\.js$/, //匹配的模块正则
  6. use: [ //匹配到后应用的规则模块
  7. { //其中一个规则
  8. loader: "模块路径", //loader模块的路径,该字符串会被放置到require中
  9. options: { //向对应loader传递的额外参数
  10. changeVar:'自定义字符串'
  11. }
  12. }
  13. ]
  14. }
  15. ]
  16. }
  17. }

image.png
test-loader.js

  1. var loaderUtils = require("loader-utils");
  2. module.exports = function(sourceCode){
  3. //sourceCode : 变量 a = 1;
  4. console.log("test-loader运行了")
  5. var options = loaderUtils.getOptions(this);// 获取loader配置的option对象
  6. console.log(options)
  7. var reg = new RegExp(options.changeVar, "g");
  8. return sourceCode.replace(reg, "var");
  9. }

图片处理的loader

  1. var loaderUtils = require('loader-utils');
  2. function loader(buffer){
  3. const content=getFilePath.call(this,buffer);
  4. return `module.exports=\'${content}\'`;
  5. }
  6. loader.raw=true;// 该loader处理原始数据,不然的是图片的乱码(buffer转换成string的结果)
  7. module.exports=loader;
  8. function getBase64(buffer){
  9. return "data:image/png;base64,"+buffer.toString("base64");
  10. }
  11. function getFilePath(buffer){
  12. const fileName loaderUtils.interpolateName(this,"[contenthash:6].[ext]",{
  13. content:buffer;
  14. })
  15. this.emitFile(fileName,buffer)
  16. }

简化配置

  1. module.exports = {
  2. module: { //针对模块的配置,目前版本只有两个配置,rules、noParse
  3. rules: [ //模块匹配规则,可以存在多个规则
  4. { //每个规则是一个对象
  5. test: /\.js$/, //匹配的模块正则
  6. use: ["模块路径1", "模块路径2"]//loader模块的路径,该字符串会被放置到require中
  7. }
  8. ]
  9. }
  10. }