Sunday, September 15, 2019

How to obfuscate or minify react javascript source code?


First of all, what is obfuscation of javascript code?

Obfuscation is the deliberate act of creating obfuscated code, i.e. source or machine code that is difficult for humans to understand. It is something similar to encryption however machine can understand the code and able to execute the code.

For example -- Original code:

function hello(name) {
console.log('Hello, ' + name);
}
hello('New user');
After Obfuscation:
eval(function(p,a,c,k,e,d{e=function(c{returnc};if(!''.replace(/^/,String)){while(c--){d=k||c}k=[function(e){return d[e]}];e=function({return'\\w+'};c=1};while(c--){if(k{p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k)}}return p}('3 0(1{2.4(\'5,\'+1)}0(\'76\');',8,8,'hello|name|console|function|log|Hello|user|New'.split('|'),0,{}))
What is minifies source code?
Minification is performed after the code for a web application is written, but before the application is deployed. When a user requests a webpage, the minified version is sent instead of the full version, resulting in faster response times and lower bandwidth costs. Minification is used in websites ranging from small personal blogs to multi-million user services.

Minification also a type of obfuscation here empty spaces will be removed and variables will be renamed.
React minifies the code during the build and generates source maps. JS ends up being sort of obfuscated as a byproduct of minification, not because of secrecy (well, that too, to some extend). That way, the end users are able to load scripts faster than if they were not minified, and you (and everybody else) get to navigate around original code when you (or they) open Developer Tools.

If you take a look in build/static/js directory after the build, there are pairs of .js and .mapfiles. JS files are loaded with your website, and .map files are loaded on demand, when Developer Tools are opened.
To disable sourcemap generation, run your build with GENERATE_SOURCEMAP environment variable set to false.
GENERATE_SOURCEMAP=false npm run build
or
GENERATE_SOURCEMAP=false yarn build
or make it part of build script in package.json
  {
    
    "scripts": {
      
-     "build": "react-scripts build"
+     "build": "GENERATE_SOURCEMAP=false react-scripts build"
    }
  }
If you omit the SOURCEMAP generation, .map files will not end up in production, and your original source code will not be available for anyone (including you).

No comments:

Post a Comment