const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { Compilation } = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const TerserWebpackPlugin = require('terser-webpack-plugin');
class MyPlugin {
apply(compiler) {
console.log('MyPlugin Start...');
compiler.hooks.thisCompilation.tap('MyPlugin', (compilation) => {
compilation.hooks.processAssets.tap(
{
name: 'MyPlugin',
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets) => {
console.log('List of assets and their sizes:');
Object.entries(assets).forEach(([pathname, source]) => {
console.log(`— ${pathname}: ${source.size()} bytes`);
if (pathname.endsWith('.js')) {
const withoutComments = source
.source()
.replace(/\/\*\*+\*\//g, '');
compilation.assets[pathname] = {
source: () => withoutComments,
size: () => withoutComments.length,
};
}
});
},
);
});
}
}
module.exports = {
mode: 'none',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
},
devtool: 'nosources-source-map',
devServer: {
hot: true,
open: true,
},
optimization: {
minimizer: [
new TerserWebpackPlugin({
terserOptions: {
compress: {
pure_funcs: ['console.log'],
},
},
}),
new OptimizeCssAssetsWebpackPlugin(),
],
},
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
{
test: /(\.png|\.jpg|\.jpeg)$/,
use: {
loader: 'url-loader',
options: {
limit: 100 * 1024,
},
},
},
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'webpack plugin sample',
template: './index.html',
}),
new CopyWebpackPlugin({
patterns: [
{
from: path.join(__dirname, 'public'),
to: __dirname + '/dist',
},
],
}),
new MiniCssExtractPlugin(),
],
};