美文网首页
webpack 简单插件和loader 配置

webpack 简单插件和loader 配置

作者: aaagu1234 | 来源:发表于2022-03-13 09:22 被阅读0次

    vue.config.js 配置

    const { defineConfig } = require('@vue/cli-service')
    const MyWebpackPlugin = require('./src/plugins/MyWebpackPlugin')
    const path = require('path')
    module.exports = defineConfig({
     
        transpileDependencies: true,
        productionSourceMap: false,
          configureWebpack: config =>  {
            config.module.rules.push({
              test: /\.js$/,
              use: [{
                loader: path.resolve(__dirname, './src/loader/MyLoader.js'),  
                options: {
                  name: '我在做一个loader测试'
                }
              }]
            })
            config.plugins.push(new MyWebpackPlugin());
          },
        publicPath: process.env.NODE_ENV === 'production'
        ? ''
        : '', // 构建好的文件输出到哪里
    })
    

    MyLoader.js

    const loaderUtils = require('loader-utils')
    module.exports = function (source) {
        const options = loaderUtils.getOptions(this)
        const result = source.replace('loader', options.name)// 找到loader 替换掉
        this.callback(null, result);
    }
    

    MyWebpackPlugin.js

    class MyWebpackPlugin {
        apply(compiler) {
           
            compiler.hooks.emit.tapAsync('MyWebpackPlugin', (compilation, callback) =>{
                const manifest = {};
                
                for (const name of Object.keys(compilation.assets)) {
                    manifest[name] = compilation.assets[name].size(); // 将生成文件的文件名和大小写入manifest对象       
                }
                compilation.assets['manifest.json'] = {
                    source() {
                        return JSON.stringify(manifest);
                    },
                    size() {
                        return this.source().length;
                    }
                };
                callback();
            });
        }
    }
    module.exports = MyWebpackPlugin;
    

    相关文章

      网友评论

          本文标题:webpack 简单插件和loader 配置

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