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;
网友评论