Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Add Obfuscation To Webpack Build

After setting up Webpack in my project, the first thing I wanted to do was add an obfuscation step, making it a lot harder for someone to just copy a lot of my work.

Adding obfuscation to your Webpack build process is actually really easy. In this tutorial we will be adding obfuscation through the webpack-obfuscator NPM package.

Steps

Navigate to your project and install the required packages as dev dependencies.

npm install --save-dev javascript-obfuscator webpack-obfuscator

Open your webpack.config.js file:

editor webpack.config.js

Add the following to above your module.exports line

var WebpackObfuscator = require('webpack-obfuscator');

e.g.

const path = require('path');
var WebpackObfuscator = require('webpack-obfuscator');

module.exports = {
    entry: './ts/index.ts',

Add Plugin

Add the following plugin to the plugins array (you may need to create it)

new WebpackObfuscator({rotateStringArray: true}, []);

The second parameter takes a list of JS files to ignore. Since we don't have any, it is empty for us.

E.g:

module.exports = {
    entry: './ts/index.ts',
    plugins: [
        new WebpackObfuscator({rotateStringArray: true}, [])
    ],

Add Rule

Finally, we then add the following rule block:

{
    enforce: 'post',
    use: {
        loader: WebpackObfuscator.loader,
        options: {
            rotateStringArray: true
        }
    }
}

e.g.

module.exports = {
    entry: './ts/index.ts',
    plugins: [
        new WebpackObfuscator({rotateStringArray: true}, [])
    ],
    module: {
        rules: [
            {
                use: 'ts-loader',
                exclude: /node_modules/,
            },
            {
                enforce: 'post',
                use: {
                    loader: WebpackObfuscator.loader,
                    options: {
                        rotateStringArray: true
                    }
                }
            }
        ],
    },
Last updated: 18th July 2021
First published: 18th July 2021