美文网首页
Hello Webpack Plugin - AssetsCop

Hello Webpack Plugin - AssetsCop

作者: 坚果jimbowhy | 来源:发表于2019-07-19 17:07 被阅读0次

    Hello Webpack Plugin

    Webpack Internal Plugin Relation
    WebPack 插件开发实例
    Webpack API
    Webpack Modules
    File System
    child_process
    从Webpack源码探究打包流程

    Introduction

    Webpack 插件开发可以参考官方提供的 html-webpack-pluginclean-webpack-pluginwebpack-manifest-plugin 这些插件作为参考,推荐使用 ES6 语法写插件,Webpack 2.0 就开始支持 ES6。

    其次要了解 Webpack 内部插件与钩子关系,参考[Webpack Internal Plugin Relation],了解 CompolationCompilerParserMainTemplate 基本对象结构。

    Webpack 在执行过程不同的阶段执行插件方法,开始时执行 apply(compiler) 方法会将当前的编译器实例传入,编译器包含了一组钩子函数 compiler.hooks 供插件使用。compiler.options 包含了 Webpack 的配置文件内容,这些配置拼合了默认的选项。

    实列化 Webpack 时,没有设置回调函数,Webpack 就会返回一个 Compiler 实例:

    const webpack = require('webpack');
    
    const compiler = webpack({
      // Configuration Object
    });
    
    compiler.run((err, stats) => { // Stats Object
      // ...
    });
    
    const watching = compiler.watch({
      // Example watchOptions
      aggregateTimeout: 300,
      poll: undefined
    }, (err, stats) => { // Stats Object
      // Print watch/build result here...
      console.log(stats);
    });
    

    基于 Node.js, Compiler 实例提供了基本的文件系统 inputFileSystem,outputFileSystem,可以这样来定制:

    const MemoryFS = require('memory-fs');
    const webpack = require('webpack');
    
    const fs = new MemoryFS();
    const compiler = webpack({ / options / });
    
    compiler.outputFileSystem = fs;
    compiler.run((err, stats) => {
      // Read the output later:
      const content = fs.readFileSync('...');
    });
    

    在使用 webpack-dev-server 开发时,就是使用 CachedInputFileSystemMemoryFileSystem。Webpack 内部还实现了几个文件系统 NodeWatchFileSystemNodeOutputFileSystemNodeJsInputFileSystem 用于不同的场景。对磁盘文件的读写还是通过 Node.js 提供的 [File System] 文件系统模块实现的。

    完成后要执行的动作通过 compiler.hooks.done 钩子来注册,Webpack 会将 Compilation 实例传入。compilation.hooks 也提供了一些钩子函数。注册钩子的方法参考以下代码,不同钩子回调函数的参数会有所差别:

    compiler.hooks.someHook.tap('MyPlugin', (params) => {
    
    });
    
    compilation.hooks.buildModule.tap('MyPlugin',
      module => {
        module.useSourceMap = true;
      }
    );
    

    Webpack 的 Module 是模块化编程的基本单元结构,支持的模块类型有 CoffeeScript、 TypeScript、 ESNext (Babel)、 Sass、 Less、 Stylus 等等,Webpack 系统的 Loader 也是模块的一种。在 buildModule 钩子中可以读取 module.typemodule.constructor 确定模块类型。

    compiler.hooks.done 钩子在编译完成时执行,回调参数是一个统计信息对象,compilation 中有包含了 compiler 和编译模块 modules 信息:

    {
        compilation: ...
        hash: '00354804c2f21f00c528',
        startTime: 1563516897225,
        endTime: 1563516905223
    }
    

    关键钩子作用 钩子类型 回调参数 解析
    beforeRun AsyncSeriesHook Compiler 运行前的准备活动,主要启用了文件读取的功能。
    run AsyncSeriesHook Compiler 跑起来了,在编译之前有缓存,则启用缓存,这样可以提高效率。
    beforeCompile AsyncSeriesHook params 开始编译前的准备,创建的ModuleFactory,创建Compilation,并绑定ModuleFactory到Compilation上。
    compile SyncHook params 编译了
    make AsyncParallelHook compilation 从Compilation的addEntry函数,开始构建模块
    afterCompile AsyncSeriesHook compilation 编译结束了
    shouldEmit SyncBailHook compilation 获取compilation发来的电报,确定编译时候成功,是否可以开始输出了。
    emit AsyncSeriesHook compilation 输出文件了
    afterEmit AsyncSeriesHook compilation 输出完毕
    done AsyncSeriesHook Stats 无论成功与否,一切已尘埃落定。

    Coding Now

    现在就来写一个插件,用来将项目根目录下的 index.html 模板拷贝到发布目录下。利用 Shell 来拷贝 public 目录的资源。在 Node.js 中使用 child_process 执行 shell 有三种方法,spawn,exec和execFile。假定 Windows 系统,借用了 xcopy 命令来复制目录结构。同时使用了 iconv-lite 做默认的 Windows 系统 GB2312 编码的默认的 Node.js 编码 UTF-8 的转换。

    const fs = require('fs');
    const exec = require('child_process').execSync;
    var iconv = require('iconv-lite');
    
    class AssetsCopier{
      constructor(options){
        this.options = options || {};
        console.log('Plugin options', this.options);
      }
    
      apply(compiler){
        let path = compiler.options.output.path;
        let buf = exec(`xcopy ${process.cwd()}\\public ${path} /Y /S /I`, err => {
          if(err) console.log(err);
        });
        let str = iconv.decode(buf, "gb2312");
        console.log("✓ apply", str);
        // fs.copyFile(src, dest[, flags], callback)  
        fs.readFile(process.cwd()+'/index.html', 'utf8', function (err, data) {
          if (err) return console.log("HTML Template not found "+err.path);
          fs.writeFile(path+'/index.html', data, err => {
            console.log( err? "Fail to copy index.html":"Copy index.html to "+path)
          });
        });
    
        if (compiler.hooks) {
          compiler.hooks.done.tap('AssetsCopier', this.onDone);
          // compiler.hooks.compilation.tap('AssetsCopier', this.onCompilation);
          compiler.hooks.afterResolvers.tap('AssetsCopier', this.onAfterResolve);
        // } else { for old webpack
        //   compiler.plugin('done', this.onDone);
        //   compiler.plugin('compilation', this.onCompilation);
        //   compiler.plugin('normal-module-factory', (nmf) => {
        //     nmf.plugin('after-resolve', this.onAfterResolve);
        //   });
        }
      }
    
      onAfterResolve(compiler){
        console.log("✓ onAfterResolve");
      }
      onCompilation(compilation, compilationParams){
        console.log("✓ onCompilation");
        compilation.hooks.buildModule.tap('AssetsCopier',
          module => {
            console.log(`\n✓ buildModule ${module.type}\n`, module.constructor.toString().split("{")[0]);
          }
        );
      }
      onDone(stats){
        console.log("✓ onDone");
      }
    }
    
    module.exports = AssetsCopier;
    

    现在,把以上代码保存到 assets-copier.js 并在 Webpack 配置文件中引入插件,然后就可以源打包,Webpack 就会执行插件了。

    const AssetsCopier  = require("./assets-copier");
    
    module.exports = {
        // ...
        plugins: [
            new AssetsCopier (),
        ]
    }
    
    AssetsCopier

    API

    lib/Compiler.js

    创建的hook(钩子)

    Compiler.hooks.additionalPass

    Compiler.hooks.afterCompile

    Compiler.hooks.afterEmit

    Compiler.hooks.afterEnvironment

    Compiler.hooks.afterPlugins

    Compiler.hooks.afterResolvers

    Compiler.hooks.beforeCompile

    Compiler.hooks.beforeRun

    Compiler.hooks.compilation

    Compiler.hooks.compile

    Compiler.hooks.contextModuleFactory

    Compiler.hooks.done

    Compiler.hooks.emit

    Compiler.hooks.entryOption

    Compiler.hooks.environment

    Compiler.hooks.failed

    Compiler.hooks.invalid

    Compiler.hooks.make

    Compiler.hooks.normalModuleFactory

    Compiler.hooks.run

    Compiler.hooks.shouldEmit

    Compiler.hooks.thisCompilation

    Compiler.hooks.watchClose

    Compiler.hooks.watchRun

    无注册的hook(钩子)

    调用的hook(钩子)

    Compiler.call.additionalPass - callAsync

    Compiler.call.afterCompile - callAsync

    Compiler.call.afterEmit - callAsync

    Compiler.call.beforeCompile - callAsync

    Compiler.call.beforeRun - callAsync

    Compiler.call.childCompiler - call

    Compiler.call.compilation - call

    Compiler.call.compile - call

    Compiler.call.contextModuleFactory - call

    Compiler.call.done - callAsync

    Compiler.call.emit - callAsync

    Compiler.call.make - callAsync

    Compiler.call.needAdditionalPass - call

    Compiler.call.normalModuleFactory - call

    Compiler.call.run - callAsync

    Compiler.call.shouldEmit - call

    Compiler.call.thisCompilation - call

    lib/Compilation.js

    创建的hook(钩子)

    Compilatio.hooks.additionalAssets

    Compilatio.hooks.additionalChunkAssets

    Compilatio.hooks.advancedOptimizeModuleOrder

    Compilatio.hooks.afterChunks

    Compilatio.hooks.afterHash

    Compilatio.hooks.afterOptimizeAssets

    Compilatio.hooks.afterOptimizeChunkAssets

    Compilatio.hooks.afterOptimizeChunkIds

    Compilatio.hooks.afterOptimizeChunkModules

    Compilatio.hooks.afterOptimizeChunks

    Compilatio.hooks.afterOptimizeDependencies

    Compilatio.hooks.afterOptimizeExtractedChunks

    Compilatio.hooks.afterOptimizeModuleIds

    Compilatio.hooks.afterOptimizeModules

    Compilatio.hooks.afterOptimizeTree

    Compilatio.hooks.afterSeal

    Compilatio.hooks.assetPath

    Compilatio.hooks.beforeChunkAssets

    Compilatio.hooks.beforeChunkIds

    Compilatio.hooks.beforeChunks

    Compilatio.hooks.beforeHash

    Compilatio.hooks.beforeModuleAssets

    Compilatio.hooks.beforeModuleIds

    Compilatio.hooks.buildModule

    Compilatio.hooks.childCompiler

    Compilatio.hooks.chunkAsset

    Compilatio.hooks.chunkHash

    Compilatio.hooks.contentHash

    Compilatio.hooks.dependencyReference

    Compilatio.hooks.failedModule

    Compilatio.hooks.finishModules

    Compilatio.hooks.finishRebuildingModule

    Compilatio.hooks.moduleAsset

    Compilatio.hooks.moduleIds

    Compilatio.hooks.needAdditionalPass

    Compilatio.hooks.needAdditionalSeal

    Compilatio.hooks.normalModuleLoader

    Compilatio.hooks.optimize

    Compilatio.hooks.optimizeAssets

    Compilatio.hooks.optimizeChunkAssets

    Compilatio.hooks.optimizeChunkIds

    Compilatio.hooks.optimizeChunkModules

    Compilatio.hooks.optimizeChunkModulesAdvanced

    Compilatio.hooks.optimizeChunkModulesBasic

    Compilatio.hooks.optimizeChunkOrder

    Compilatio.hooks.optimizeChunks

    Compilatio.hooks.optimizeChunksAdvanced

    Compilatio.hooks.optimizeChunksBasic

    Compilatio.hooks.optimizeDependencies

    Compilatio.hooks.optimizeDependenciesAdvanced

    Compilatio.hooks.optimizeDependenciesBasic

    Compilatio.hooks.optimizeExtractedChunks

    Compilatio.hooks.optimizeExtractedChunksAdvanced

    Compilatio.hooks.optimizeExtractedChunksBasic

    Compilatio.hooks.optimizeModuleIds

    Compilatio.hooks.optimizeModuleOrder

    Compilatio.hooks.optimizeModules

    Compilatio.hooks.optimizeModulesAdvanced

    Compilatio.hooks.optimizeModulesBasic

    Compilatio.hooks.optimizeTree

    Compilatio.hooks.rebuildModule

    Compilatio.hooks.record

    Compilatio.hooks.recordChunks

    Compilatio.hooks.recordHash

    Compilatio.hooks.recordModules

    Compilatio.hooks.reviveChunks

    Compilatio.hooks.reviveModules

    Compilatio.hooks.seal

    Compilatio.hooks.shouldGenerateChunkAssets

    Compilatio.hooks.shouldRecord

    Compilatio.hooks.succeedModule

    Compilatio.hooks.unseal

    调用的hook(钩子)

    Compilation.call.additionalAssets - callAsync

    Compilation.call.additionalChunkAssets - call

    Compilation.call.advancedOptimizeModuleOrder - call

    Compilation.call.afterChunks - call

    Compilation.call.afterHash - call

    Compilation.call.afterOptimizeAssets - call

    Compilation.call.afterOptimizeChunkAssets - call

    Compilation.call.afterOptimizeChunkIds - call

    Compilation.call.afterOptimizeChunkModules - call

    Compilation.call.afterOptimizeChunks - call

    Compilation.call.afterOptimizeDependencies - call

    Compilation.call.afterOptimizeModuleIds - call

    Compilation.call.afterOptimizeModules - call

    Compilation.call.afterOptimizeTree - call

    Compilation.call.afterSeal - callAsync

    Compilation.call.beforeChunkAssets - call

    Compilation.call.beforeChunkIds - call

    Compilation.call.beforeChunks - call

    Compilation.call.beforeHash - call

    Compilation.call.beforeModuleAssets - call

    Compilation.call.beforeModuleIds - call

    Compilation.call.buildModule - call

    Compilation.call.chunkAsset - call

    Compilation.call.chunkHash - call

    Compilation.call.contentHash - call

    Compilation.call.dependencyReference - call

    Compilation.call.failedModule - call

    Compilation.call.finishModules - call

    Compilation.call.finishRebuildingModule - call

    Compilation.call.moduleAsset - call

    Compilation.call.moduleIds - call

    Compilation.call.needAdditionalSeal - call

    Compilation.call.optimize - call

    Compilation.call.optimizeAssets - callAsync

    Compilation.call.optimizeChunkAssets - callAsync

    Compilation.call.optimizeChunkIds - call

    Compilation.call.optimizeChunkModules - call

    Compilation.call.optimizeChunkModulesAdvanced - call

    Compilation.call.optimizeChunkModulesBasic - call

    Compilation.call.optimizeChunkOrder - call

    Compilation.call.optimizeChunks - call

    Compilation.call.optimizeChunksAdvanced - call

    Compilation.call.optimizeChunksBasic - call

    Compilation.call.optimizeDependencies - call

    Compilation.call.optimizeDependenciesAdvanced - call

    Compilation.call.optimizeDependenciesBasic - call

    Compilation.call.optimizeModuleIds - call

    Compilation.call.optimizeModuleOrder - call

    Compilation.call.optimizeModules - call

    Compilation.call.optimizeModulesAdvanced - call

    Compilation.call.optimizeModulesBasic - call

    Compilation.call.optimizeTree - callAsync

    Compilation.call.rebuildModule - call

    Compilation.call.record - call

    Compilation.call.recordChunks - call

    Compilation.call.recordHash - call

    Compilation.call.recordModules - call

    Compilation.call.reviveChunks - call

    Compilation.call.reviveModules - call

    Compilation.call.seal - call

    Compilation.call.shouldGenerateChunkAssets - call

    Compilation.call.shouldRecord - call

    Compilation.call.succeedModule - call

    Compilation.call.unseal - call

    相关文章

      网友评论

          本文标题:Hello Webpack Plugin - AssetsCop

          本文链接:https://www.haomeiwen.com/subject/xvpslctx.html