使用 插件实现过去除打包后的js文件中的注释

    插件是一个带有 apply 方法的 class。

    1. 在 自定义的 插件 js 文件中,module.exports 一个 class,因为插件使用的时候要被 new
    2. class 含有一个 apply 方法
    3. 这个方法 接受一个 compiler 参数对象【compiler 对象中有各种钩子,在webpack 运行阶段被触发,实现这些钩子的核心是 tapable】
    4. 在 compiler 对象上 插入指定的 钩子
    5. 在钩子的回调函数中,拿到 compilation 对象
    6. 通过这个 对象可以拿到打包后的文件信息,比如 assets、modules、chunks 的信息
    7. 插件在 constructor 中可以接受参数
    1. // 实现一个 删除 打包后的 js 文件中的 注释
    2. class removeComments {
    3. constructor(params) {
    4. // 通过 params 可以拿到参数
    5. console.log('参数', params);
    6. }
    7. apply(compiler) {
    8. compiler.hooks.emit.tap('removeComments', compilation => {
    9. for (let fileName in compilation.assets) {
    10. if (fileName && fileName.endsWith('.js')) {
    11. // 获取源文件
    12. const source = compilation.assets[fileName].source();
    13. const withoutComments = source.replace(/\/\*+\*\//g, '')
    14. /******/
    15. compilation.assets[fileName] = {
    16. source: () => withoutComments,
    17. size: () => withoutComments.length
    18. }
    19. }
    20. }
    21. })
    22. }
    23. }
    24. module.exports = removeComments;
    25. // 使用
    26. const RemoveComments = require('./src/plugins/removeComments')