Search code examples
javascripthtmlwebpackminify

Using HtmlWebpackPlugin with inject = true does not minify ES6 code


I am trying to create a html file from a template file, injecting some JavaScript inline into the html file.

This works great, other than when I get to some ES6 syntax in my js file async in particular in my example. It then leaves all the code unminified in that particular block of code.

I was wondering if there is a way to transpile my code perhaps before it gets minified?

Any help would be greatly appreciated.

My webpack.config.js file looks as follows

var path = require('path');
var fs = require("fs");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');
const Uglify = require("uglifyjs-webpack-plugin");

module.exports = {
    context: __dirname,
    entry: './TestFile/index.js',
    output: {
        path: path.resolve(__dirname, 'TestFile')
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: 'babel-loader',
                exclude: /node_modules/,
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'TestFile.html',
            template: './TestFile/TestFileTemplate.html',
            inject: true,
            jquery: fs.readFileSync('./TestFile/js/jquery.js', 'utf8'),
            gds: fs.readFileSync('./TestFile/js/extras.js', 'utf8'),
            style: fs.readFileSync('./TestFile/css/style.css', 'utf8'),
            minify: {
                html5: true,
                collapseWhitespace: true,
                minifyCSS: true,
                minifyJS: true,
                removeScriptTypeAttributes: true,
                removeStyleLinkTypeAttributese: true,
                useShortDoctype: true
            }
        })
    ]
};

Solution

  • I assume you want to minify the file here:

    gds: fs.readFileSync('./TestFile/js/extras.js', 'utf8'),
    

    You can use babel to transpile the file content:

    gds: require("@babel/core").transformSync(fs.readFileSync('./TestFile/js/extras.js', 'utf8'), {
      "presets": ["@babel/preset-env"]
    }).code;
    

    There is also html-webpack-inline-source-plugin. It might be a cleaner way to inline files.