Search code examples
javascripthtmlcssminify

How to minify my files before deploying them to the server


I want to enhance the performance of my front-end website and I found that one of the best practices is minifying my files. After searching I decided to use terser package. I've never done this before so some points are confusing me.

1- Do I have to change the script and CSS link in the HTML header with the minified files before building the project (I'm using parcel)?

so they will become :

<!-- <link rel="stylesheet" href="old-style.css" /> -->
<link rel="stylesheet" href="style.min.css" />
<!-- <script type="module" defer src="old-app.js"></script> -->
<script type="module" defer src="app.min.js"></script>

2- In my case, I have app.js file that imports other files:

import { revealContent } from "./script/revealContent.js";
import { gsapAnimation } from "./script/gsapAnimation.js";
import { map } from "./script/map.js";
import { showPopup, closePopup } from "./script/reservationPopup.js";
import { validateDate, validatePhone, validateForm, errorMessage} from "./script/validateData.js";
import { slider } from "./script/slider.js";

should I minify them before app.js or the order doesn't matter?

3- If the previous script files get minified and they are now inside ./script/min-script/ folder, is terser able to know their new destination when minifying app.js so the process gets done correctly?

4- After finishing the minifying process, I guess the parcel build command should be for the new minified HTML that has the links to minified CSS/JavaScript files right?

I'd highly appreciate your help


Solution

  • hey there! when you minify your CSS and JavaScript files, you should update the references in your HTML to point to the minified versions. So, in your HTML, use links like:

    <link rel="stylesheet" href="style.min.css" />
    

    If you move the minified script files to a different folder (e.g., "./script/min-script/"), you need to update the import paths in "app.js" to reflect the new location. Terser doesn't automatically know the new destination of the files, so make sure to adjust the import paths accordingly.

    For example, if your "revealContent.js" file was moved to "./script/min-script/revealContent.js", update the import in "app.js" like this:

    import { revealContent } from "./script/min-script/revealContent.js";
    

    After the minification process, you should indeed use the parcel build command for the updated HTML file that references the minified CSS and JavaScript files. Ensure that your HTML file points to the correct paths for the minified files.

    parcel build path/to/your/minified/index.html