This is continues of my previous post about how to remove unused CSS and convert unclear JavaScript to protect your source code in the post-build process. If you are using CSS libraries like Bootstrap, Tailwind CSS, etc.. and sometimes multiple frameworks. But your application components are not using all of the styles and it adds more weight to the application performance. This post will explain how to configure the React post-build process to remove unused CSS and hidden JavaScript files that enhance the application security and definitely improve the app loading time and save the overall bandwidth cost.
GitHub Source
Live Demo
Requirements
- Node Latest
Create React Project
npx create-react-app react-post-build
cd react-post-build
cd react-post-build
App.js
Update with simple HTML tags.
import './App.css';
export default App;
function App() {
return (
<div className="App">
<h1>Welcome to React Post Build</h1>
</div>
);
}
Start React Project
npm start
Install Bootstrap Framework
Execute the following npm command to install the Boostrap and icons.
npm install bootstrap bootstrap-icons
Configure Bootstrap with Application
Import Bootstrap CSS and apply classes to HTML.
import './App.css';
export default App;
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-icons/font/bootstrap-icons.css';
function App() {
return (
<div className="App">
<div class="container">
<h1>
<i class="bi bi-robot"></i> Welcome to React Build CSS
</h1>
<div>
<button class="btn btn-success" type="submit">
<i class="bi bi-bug-fill"></i> Test Button
</button>
</div>
</div>
</div>
);
}
Remove Unused CSS
We are going to implement this with the production build process.
PurgeCSS
This tool will analyze JavaScript and HTML file and removes the unused CSS.
npm install purgecss --save-dev
You need the following dependency for executing the PurgeCSS command
npm install fs child_process path --save-dev
purgecss.js
Create an external script file, here the following script analyzes the build folder and minimizes the CSS file. Create a scripts folder under the project src directory.
const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
// find the styles css file
const files = getFilesFromPath('./build/static/css/', '.css');
let data = [];
if (!files && files.length <= 0) {
console.log('cannot find style files to purge');
return;
}
for (let f of files) {
// get original file size
const originalSize = getFilesizeInKiloBytes('./build/static/css/' + f) + 'kb';
var o = { file: f, originalSize: originalSize, newSize: '' };
data.push(o);
}
console.log('Run PurgeCSS...');
exec(
'./node_modules/purgecss/bin/purgecss.js -css build/static/css/*.css --content build/index.html build/static/js/*.js -o build/static/css/',
function (error, stdout, stderr) {
console.log('PurgeCSS done');
console.log(data);
for (let d of data) {
// get new file size
const newSize = getFilesizeInKiloBytes('./build/static/css/' + d.file) + 'kb';
d.newSize = newSize;
}
console.table(data);
}
);
function getFilesizeInKiloBytes(filename) {
var stats = fs.statSync(filename);
var fileSizeInBytes = stats.size / 1024;
return fileSizeInBytes.toFixed(2);
}
function getFilesFromPath(dir, extension) {
let files = fs.readdirSync(dir);
return files.filter((e) => path.extname(e).toLowerCase() === extension);
}
package.json
Update the package scripts and include purgecss command with the build command.
"scripts": { },
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"purgecss": "node ./src/scripts/purgecss.js",
"postbuild": "npm run purgecss"
Build Project
Now the following command will execute the project build with purge CSS commands.
npm run build
After the application build, this will remove the unused CSS and creates a new small(9KB) CSS file Converted CSS File
Obfuscate JavaScript
This makes your code harder to copy and prevents people from stealing your work. This tool helps you to convert regular JavaScript to a difficult way to read. It enhances security and provides protection for your source code.
Install Javascript Obfuscator
Include javascript-obfuscator plugin in dev dependencies
npm install javascript-obfuscator --save-dev
obfuscate.js
External executable files and analyze the build files and convert all of the JavaScript files. Copy this file under the application src/scripts folder.
const fs = require("fs");
const path = require("path");
const JavaScriptObfuscator = require("javascript-obfuscator");
const settings = {
compact: true,
};
function obfuscateDir(dirPath) {
let dirents = fs.readdirSync(dirPath, {
encoding: "utf8",
withFileTypes: true,
});
for (let i = 0; i < dirents.length; i++) {
let dirent = dirents[i];
if (dirent.isDirectory()) {
obfuscateDir(path.join(dirPath, dirent.name));
continue;
}
if (path.extname(dirent.name) !== ".js") continue;
const filePath = path.join(dirPath, dirent.name);
const content = fs.readFileSync(filePath, { encoding: "utf8" });
const obfuscator = JavaScriptObfuscator.obfuscate(content, settings);
const obfuscatedCode = obfuscator.getObfuscatedCode();
fs.writeFileSync(filePath, obfuscatedCode, {
encoding: "utf8",
flag: "w+",
});
console.log("🤖 🤖 🤖 Done!");
}
}
obfuscateDir(path.join(__dirname, "../../build"));
Obfuscate JavaScript File
Copy executable script files under src/scripts directory
Final package.json
Combine all the external scripts and include the post-build command.
"scripts": { },
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"purgecss": "node ./src/scripts/purgecss.js",
"obfuscate": "node ./src/scripts/obfuscate.js",
"postbuild": "npm run purgecss && npm run obfuscate"
Note: If you are using translated language file, don't include any CSS styles. Purge CSS analyzes only JS and HTML files.
Nice information given
ReplyDelete