Skip to content

Instantly share code, notes, and snippets.

@szuc
Created March 29, 2020 13:12
Show Gist options
  • Save szuc/cb1203c35c5259023515247c8c9ecb96 to your computer and use it in GitHub Desktop.
Save szuc/cb1203c35c5259023515247c8c9ecb96 to your computer and use it in GitHub Desktop.
Production Webpack config file for Wordpress plugin development
/**
* Final production version.
* Minify CSS and JS
* Babel and Browser prefix for backwards compatibility
* Image minification and copy files to assets
*/
const path = require("path");
const webpack = require('webpack'); // to access built-in plugins
// deletes the assets
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// extracts css into a separate file rather than being in the js file
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// minifies css
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
// minifies js
const TerserPlugin = require('terser-webpack-plugin');
// enables autoprefixing and other compatibility fixes from postcssPresetEnv
const postcss = require('postcss');
const postcssPresetEnv = require('postcss-preset-env');
// Copy files from one folder to another
const CopyPlugin = require('copy-webpack-plugin');
// Image optimization
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const glob = require('glob');
module.exports = {
// splitting into two entries generates multiple css files but unfortunately, also two js files
entry: {
myApp_admin: "./src/scss/admin_styles.scss",
myApp: "./src/index.js"
},
output: {
filename: "js/[name].js",
path: path.resolve(__dirname, "assets")
},
mode: 'production',
plugins: [
new webpack.ProgressPlugin(),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: "css/[name].css"
}),
// loads the images into the flow to be processed by the imagemin
new CopyPlugin([
{
from: 'img/**/*',
to: 'img/[name].[ext]',
context: 'src/',
}
]),
new ImageminPlugin({
test: /\.(jpe?g|png|gif|svg)$/i,
bail: false, // Ignore errors on corrupted images
cache: true,
imageminOptions: {
plugins: [
["gifsicle", { interlaced: true }],
["jpegtran", { progressive: true }],
["optipng", { optimizationLevel: 5 }],
[
"svgo",
{
plugins: [
{
removeViewBox: false
}
]
}
]
]
}
})
],
optimization: {
minimizer: [
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
discardComments: true,
map: {
inline: false,
annotation: true,
},
safe: true,
},
}),
new TerserPlugin({
parallel: true,
terserOptions: {
safari10: true
}
}),
],
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env'],
}
}
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('postcss-preset-env')
]
}
},
'sass-loader',
],
},
]
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment