vincentsty
vincentsty

Reputation: 3221

Compiling or obfuscating node js

I have an existing node js backend that need to deploy on customer premise. I would like to compile/obfuscate the code before passing to client.

I do not know whether it is "compilable". But at very least i want to have only single merged code into index.js file (other javascript file all remove) that is obfuscated before passing to client. Is there any existing npm module that does that and how reliable that an obfuscated code work as it is then original code.

What are your company/ ways to deal with it when u need to pass an existing node js source code deployable at client premise.

I am much more looking at existing library that can automate the whole process. eg: npx run obfuscate-code --entrypoint.js (it will search all the import/require from node js and compile everything.

Folder structure is as follow.
    home
     - controllers (folder)
       - file1.js
       - file2.js
     - languages (folder)
       - en.js
     - services (folder)
       - service1.js
       - service2.js
     - index.js (entry point)

Upvotes: 2

Views: 3204

Answers (1)

Yak O'Poe
Yak O'Poe

Reputation: 822

You can make an executable using PKG (npm package) see => https://github.com/zeit/pkg

or webpack if you want to make a single js file that is minimized.

// webpack.config.js
const nodeExternals = require('webpack-node-externals');

module.exports = {
    mode: 'production',
    target: 'node',
    externals: [nodeExternals()],
    entry: {
        'build/output': './src/index.js'
    },
    output: {
        path: __dirname,
        filename: '[name].bundle.js',
        libraryTarget: 'commonjs2'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['env', {
                                'targets': {
                                    'node': 'current'
                                }
                            }]
                        ]
                    }
                }
            }]
    }
};

By using nodeExternals you don't put external dependencies in the main js file but you refer to node_modules.

You can use both those 2 solutions using npm run ... by adding them to your scripts section in package.json

Upvotes: 3

Related Questions