Webpack

Jun's Coding Journey·2022년 11월 20일
0

[Challenge] Youtube Clone

목록 보기
15/19

General Concept

Webpack is a static module bundler for JavaScript applications that takes all the code from an application and makes it usable in any web browser. Using webpack modules, developers can easily take chunks of code built from JavaScript and CSS code and package them to be used in websites. This makes it easier to write code as webpack takes the code and converts it to readable code for the browser.

Most developers today use framework such as react, vue, or angular where webpack is pre-installed and configured. However, it is still required to at least understand what webpack does as it is still the industry standard.

In simpler definition, webpack takes our code, transforms them to usable code, and sends the transformed code to a new directory.

Configuration

To install webpack, we use npm on our terminal.

// installing on our devDependancies
npm i webpack webpack-cli -D

We then create a webpack file.

webpack.config.js

A webpack configuration file gets two properties: entry and output.

An entry property is where we put the source code we want to process. For this process, we create a new folder that will contain all the code that will be executed by the browser. This folder usually will contain a JavaScript and CSS code. Once we finish writing this code, we will put the address of the code on the entry property.

An output property will be the directory where the source code will be sent after transformation. The output property will again have a filename property that will have a name and a path property that specifies a new directory that will be created after transformation (This folder will be created automatically).

moduel.exports = {
  entry: "./src/client/js/main.js"
  output: {
    filename: "main.js",
  	path: "./assets/js"
	},
}

To run webpack on the terminal, we need to add a script code on the package.json file. Running the command will create the output directory (the directory must be an ABSOLUTE path).

// creating an absolute directory
output: path.resolve(__dirname, "assets", "js")
// webpack code on package.json
"assets": "webpack --config webpack.config.js"

To process frontend code to reusable code on the browser, we need to define the rules on the webpack object. Rules will hold an array which will contain a list of loaders that will help transform our codebase into usuable code.

For JavaScript, we download an npm package called babel-loader. After installation, we follow the webpack documentation to create a rule for JavaScript.

npm i -D babel-loader

Don't forget to set the mode on development and not on production.

mode: "development",

Now that we can run our webpack, it is time to display the code on the browser. To do this, we need to let express.js know the existence of the transformation folder. On the server.js file, we create an app.use() function that takes this transformed directory.

app.use("/assets", express.static("assets"));

Additionally, we add the script address of our source code to the main pug.js file. This will load our JavaScript file on the browser.

script(src="/static/js/main.js")

SCSS Loader

SCSS (also known as Sass) stands for "Sassy Cascading Style Sheets". SCSS is an extension that gives you additional features to use on CSS and provides better workflow for maintaining stylesheets. With SCSS, you can reduce the amount of times you repeat yourself and ensure a clean and maintainable code.

Using SCSS together with webpack is awesome because it takes your clean SCSS code and transforms them to reusable code for any web browser.

To allow webpack to load SCSS code, we need to create a loader property for SCSS.

NOTE: the order of the loader starts from the last index of the array.

test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],

MiniCssExtractPlugin

Most of the time, we want JavaScript and CSS to work separately for better workflow. Using the MiniCssExtractPlugin, we can generate CSS code on a separate folder.

entry: "./src/client/js/main.js",
mode: "development",
plugins: [
  new MiniCssExtractPlugin({
    filename: "css/styles.css",
  }),
],
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],

Better Developer Experience

  1. Updating webpack code files
watch: true;
  1. Ignoring nodemon (create 'nodemon.json' file)
{
  "ignore": ["webpack.config.js", "src/client/*", "assets/*"],
  "exec": "babel-node src/init.js"
}

Source Code

// webpack configuration code
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");

module.exports = {
  entry: "./src/client/js/main.js",
  mode: "development",
  watch: true,
  plugins: [
    new MiniCssExtractPlugin({
      filename: "css/styles.css",
    }),
  ],
  output: {
    filename: "js/main.js",
    path: path.resolve(__dirname, "assets"),
    clean: true,
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [["@babel/preset-env", { targets: "defaults" }]],
          },
        },
      },
      {
        test: /\.scss$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
    ],
  },
};
profile
Greatness From Small Beginnings

0개의 댓글