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, reservedStrings: [ '\s*' ]}, []);

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, reservedStrings: [ '\s*' ]}, [])
    ],

Add Rule

Finally, we then add the following rule block:

{
    enforce: 'post',
    use: {
        loader: WebpackObfuscator.loader,
        options: {
            rotateStringArray: true,
            reservedStrings: [ '\s*' ]
        }
    }
}

e.g.

module.exports = {
    entry: './ts/index.ts',
    plugins: [
        new WebpackObfuscator({rotateStringArray: true, reservedStrings: [ '\s*' ]}, [])
    ],
    module: {
        rules: [
            {
                use: 'ts-loader',
                exclude: /node_modules/,
            },
            {
                enforce: 'post',
                use: {
                    loader: WebpackObfuscator.loader,
                    options: {
                        reservedStrings: [ '\s*' ],
                        rotateStringArray: true
                    }
                }
            }
        ],
    },

References

Last updated: 28th July 2021
First published: 18th July 2021

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch