How to setup Webpack config - tutorial for beginners

This article was originally published at https://www.blog.duomly.com/what-is-webpack-and-how-to-setup-webpack/


Intro to Webpack tutorial

Webpack is a tool very often used in software development, and it’s pretty useful. For many junior and even mid developers, Webpak can be the darkest nightmare, and it was scary for me as well. By all the power, I tried to avoid setting Webpack by using tools like create-react-app to build a new ReactJS application and never have to do any changes inside the ready config, as it seemed confusing.

But for every developer, it comes the day when you just have to beat the beast and learn how it works, to set Webpack in a more efficient way for a particular project and make your software even better.

In this article, I’d like to help you with this overwhelming and confusing area of development and explain some basics about Webpack, what it is, why we use it, how it works, and the most important, how to setup Webpack.

For those of you who would like to watch instead of reading, as always, I have a video tutorial on our Youtube channel.

Let’s start!

What is webpack

Webpack is a module bundler for web applications that bundles, minify, and transpile JavaScript code to the code understandable by all the browsers. As a Javascript developer, you probably have heard about modules before. Webpack has a broad definition of what modules are, and it takes into consideration: ES modules, CommonJS modules, CSS imports, image URLs, or AMD modules.

It’s important to understand that Webpack is not used on the actual page in the production environment. It’s running during the development process. What we can see life is a code generated as a bundle by the Webpack.

How Webpack works?

Webpack goes through your application and creates a dependency graph consisting of modules that the application needs to work properly. Next, based on the dependency graph, it creates a new package, mostly it’s just one file called bundle.js, but it can also be divided into chunks, so smaller files are loaded as necessary. The package file created by Webpack is imported as a script in the HTML file of the application and makes the app working as expected.

Although since version 4.0, it’s not required to create a config file to use Webpack to bundle your project, it’s good to know what’s inside to adjust the config and get more profit from using the tools.

To be able to create a well-working config, it’s important to understand the core concepts of Webpack:

Webpack entry point indicates where Webpack should start building the dependency graph. From this point, it will find the other dependencies required to provide the proper functionality of the application. By default, it’s ./src/index.js

Webpack output is a point where the Webpack emits bundles and the name of the bundle file. By default, it’s main.js, and the folder is ./dist/, but inside the configuration file, you can place it somewhere else in the application and name the file differently.

Webpack loaders are used to process any other types of files, as Webpack by default, can recognize only JSON and Javascript. That’s why we need some additional settings for images or styles. The principal task of the loaders is to convert those sources to valid modules, which can be added to the dependency graph. There are two properties in high-level Webpack loaders configuration, test to identify which files and folders should be transformed, and use to indicate which loaders should be used for transforming.

Webpack plugins are used to perform a wider range of tasks, like bundle optimization or environment variables injection. To use plugins, we need to import them using require(), and then add it to the plugins array.

Webpack mode is a parameter that lets Webpack know what’s the environment of the application. It can have the following values: development, production or none. By default, the mode is set to production.

Well, when you understand most of the important Webpack concepts, we can jump to a practical Webpack setup.

How to setup Webpack?

At this point, I’d like to go through setting the simple Javascript application with Webpack and set by step show you how it works. For the purpose of this tutorial, I’ll be using Webpack 5.

Webpack install

Let’s start by creating a new project and initialize npm.

mkdir webpackTutorial && cd webpackTutorial

npm init -y

Next, let’s install all the necessary tools: webpack and webpack-cli.

npm install webpack webpack-cli

When this step is finished successfully, let’s create a simple project structure and a file with some dummy code.

So, let’s open the project folder, and let’s add the src folder and index.js file like below.

Duomly - Webpack setup

Inside the index.js file, let’s add a simple Javascript code to use to build our bundle and be injected into our main page.

const title = document.createElement('h3');
title.textContent = 'Webpack made easy!';

const page = document.querySelector('body');
page.append(title);

Webpack config

To start with the Webpack setup, we need one more file. Inside the root folder, let’s create the file webpack.config.js, and let’s start by setting the entry point and output for our application bundle.

const path = require('path')

module.exports = {
  entry: {
    index: path.resolve(__dirname, './src/index.js') 
  }
}

In the first line of the code, we imported the path module, which provides utilities for working with paths of files and directories. It’s a part of Node.js.

Then, we told Webpack where to look for the first file, which will be the base to create a dependency graph.

Next, we can setup the folder and file where we would like Webpack to save our bundle, and we will set it as an output.

const path = require('path')

module.exports = {
  entry: {
    index: path.resolve(__dirname, './src/index.js') 
  },
  output: {
    path: path.resolve(__dirname, './build'),
    filename: '[name].bunde.js'
  }
}

In the output part of our Webpack config, I set the location of the bundle to ./build folder instead of default ./dist, and as a filename, I passed a variable, so the [name] of our bundle file will be as defined in the entry index.bundle.js.

Right now, we can try out our Webpack bundle, as we have a minimum config ready. Let’s open package.json file, and let’s adjust it to run Webpack from the console.

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "build": "webpack"
},

When it’s ready, open the project in the console and run the following command.

npm run build

When it’s done, you should see something like the image below in your console. Also, you’ll be able to see a new folder in your application with the bundle file. Nothing interesting happened there yet, but the build exists.

Duomly - How to setup Webpack?

Webpack - Html Plugin

Right now, I’ll show you how to add plugins to your Webpack config to make it more flexible. We want to add some HTML to our application, so we need it to be generated, and for this, we need a Webpack plugin. Let’s install html-webpack-plugin.

npm install html-webpack-plugin

When that’s installed, we can go back to our config file and configure the plugin.

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  ...
  plugins: [
    new HTMLWebpackPlugin({
      template: path.resolve(__dirname, "./src/template.html")
    })
  ]
}

Before we move forward to update our build, we need actually to create our template.html file.

<!DOCTYPE html>
<html> 
  <head>
    <meta charset="UTF-8">
    <title>Hello world!</title>
  </head>
  <body>
    Hello world!
  </body>
</html>

Now, let’s build the bundle again and run the index.html file you will find in the build folder in the browser. You should be able to see the content of the HTML file we’ve created and the text we used in our index.js file.

Duomly - Webpack Tutorial

Webpack loaders

If we would like to add any other type of files like assets or CSS, we need to add loaders that allow Webpack to understand them, compile and use them. Let’s add some images to our code, and then we will need to set the assets loader.

Let’s create a new folder inside ./src, and let’s call it assets. Let’s add any image there. And next, try to import it in your index.js file, and let’s append it to our page.

import koala from './assets/koala.png'


...

const img = new Image();
img.src = koala;
page.appendChild(img);

Right now, to be able to update the bundle, you need to add a loader in your Webpack config.

module: {
  rules: [
  {
    test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
    type: 'asset/resource',
  },
],
}

Let’s run the build once again, and let’s refresh the index.js file in the browser, and then you can see your image below the text.

Now, let’s learn how to use styles with Webpack.

Webpack CSS loader

Let’s create a simple styles file, and let’s import it into our index.js file.

// style.css
body {
  text-align: center;
  margin: 20px;
}
h3 {
  color: #333333;
  background: #f5f5f5;
  padding: 20px;
}
img {
  max-height: 500px;
}

//index.js 
import './style.css';

Now, to be able to see the changes, we need to install loaders for CSS: style-loader and css-loader.

npm install css-loader style-loader

When those are installed, let’s go back to our Webpack config, and let’s add the loader rule.

module: {
  rules: [
    {
      test: /\.css$/,
      use: ["style-loader", "css-loader"]
    },
    {
      test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
      type: 'asset/resource',
    },
  ],
}

After that, we can rerun the bundle and see if our styles work.

It seems like it works!

Conclusion

Congratulations, you’ve just created a simple Webpack setup!

In this article, we went through what is Webpack and how Webpack works. Next, we went through the most important concepts of Webpack that you need to understand to build any Webpack configuration.

I hope this knowledge will help you next time when someone will start talking about Webpack. You can be as confident as never before and stop being scared of the big Webpack monster.

In my opinion, it’s not so difficult and confusing when you will know what’s the purpose of using it, how it works, and what the concepts are responsible for.

Thank you for reading,
Anna from Duomly

#webpack #javascript #web-development #html5 #html #css

What is GEEK

Buddha Community

How to setup Webpack config - tutorial for beginners

Matteo Gioioso

1607266841

Video is not displayed

Jeromy  Lowe

Jeromy Lowe

1599097440

Data Visualization in R with ggplot2: A Beginner Tutorial

A famous general is thought to have said, “A good sketch is better than a long speech.” That advice may have come from the battlefield, but it’s applicable in lots of other areas — including data science. “Sketching” out our data by visualizing it using ggplot2 in R is more impactful than simply describing the trends we find.

This is why we visualize data. We visualize data because it’s easier to learn from something that we can see rather than read. And thankfully for data analysts and data scientists who use R, there’s a tidyverse package called ggplot2 that makes data visualization a snap!

In this blog post, we’ll learn how to take some data and produce a visualization using R. To work through it, it’s best if you already have an understanding of R programming syntax, but you don’t need to be an expert or have any prior experience working with ggplot2

#data science tutorials #beginner #ggplot2 #r #r tutorial #r tutorials #rstats #tutorial #tutorials

Willie  Beier

Willie Beier

1596728880

Tutorial: Getting Started with R and RStudio

In this tutorial we’ll learn how to begin programming with R using RStudio. We’ll install R, and RStudio RStudio, an extremely popular development environment for R. We’ll learn the key RStudio features in order to start programming in R on our own.

If you already know how to use RStudio and want to learn some tips, tricks, and shortcuts, check out this Dataquest blog post.

Table of Contents

#data science tutorials #beginner #r tutorial #r tutorials #rstats #tutorial #tutorials

Tutorial: Loading and Cleaning Data with R and the tidyverse

1. Characteristics of Clean Data and Messy Data

What exactly is clean data? Clean data is accurate, complete, and in a format that is ready to analyze. Characteristics of clean data include data that are:

  • Free of duplicate rows/values
  • Error-free (e.g. free of misspellings)
  • Relevant (e.g. free of special characters)
  • The appropriate data type for analysis
  • Free of outliers (or only contain outliers have been identified/understood), and
  • Follows a “tidy data” structure

Common symptoms of messy data include data that contain:

  • Special characters (e.g. commas in numeric values)
  • Numeric values stored as text/character data types
  • Duplicate rows
  • Misspellings
  • Inaccuracies
  • White space
  • Missing data
  • Zeros instead of null values

2. Motivation

In this blog post, we will work with five property-sales datasets that are publicly available on the New York City Department of Finance Rolling Sales Data website. We encourage you to download the datasets and follow along! Each file contains one year of real estate sales data for one of New York City’s five boroughs. We will work with the following Microsoft Excel files:

  • rollingsales_bronx.xls
  • rollingsales_brooklyn.xls
  • rollingsales_manhattan.xls
  • rollingsales_queens.xls
  • rollingsales_statenisland.xls

As we work through this blog post, imagine that you are helping a friend launch their home-inspection business in New York City. You offer to help them by analyzing the data to better understand the real-estate market. But you realize that before you can analyze the data in R, you will need to diagnose and clean it first. And before you can diagnose the data, you will need to load it into R!

3. Load Data into R with readxl

Benefits of using tidyverse tools are often evident in the data-loading process. In many cases, the tidyverse package readxl will clean some data for you as Microsoft Excel data is loaded into R. If you are working with CSV data, the tidyverse readr package function read_csv() is the function to use (we’ll cover that later).

Let’s look at an example. Here’s how the Excel file for the Brooklyn borough looks:

The Brooklyn Excel file

Now let’s load the Brooklyn dataset into R from an Excel file. We’ll use the readxlpackage. We specify the function argument skip = 4 because the row that we want to use as the header (i.e. column names) is actually row 5. We can ignore the first four rows entirely and load the data into R beginning at row 5. Here’s the code:

library(readxl) # Load Excel files
brooklyn <- read_excel("rollingsales_brooklyn.xls", skip = 4)

Note we saved this dataset with the variable name brooklyn for future use.

4. View the Data with tidyr::glimpse()

The tidyverse offers a user-friendly way to view this data with the glimpse() function that is part of the tibble package. To use this package, we will need to load it for use in our current session. But rather than loading this package alone, we can load many of the tidyverse packages at one time. If you do not have the tidyverse collection of packages, install it on your machine using the following command in your R or R Studio session:

install.packages("tidyverse")

Once the package is installed, load it to memory:

library(tidyverse)

Now that tidyverse is loaded into memory, take a “glimpse” of the Brooklyn dataset:

glimpse(brooklyn)
## Observations: 20,185
## Variables: 21
## $ BOROUGH <chr> "3", "3", "3", "3", "3", "3", "…
## $ NEIGHBORHOOD <chr> "BATH BEACH", "BATH BEACH", "BA…
## $ `BUILDING CLASS CATEGORY` <chr> "01 ONE FAMILY DWELLINGS", "01 …
## $ `TAX CLASS AT PRESENT` <chr> "1", "1", "1", "1", "1", "1", "…
## $ BLOCK <dbl> 6359, 6360, 6364, 6367, 6371, 6…
## $ LOT <dbl> 70, 48, 74, 24, 19, 32, 65, 20,…
## $ `EASE-MENT` <lgl> NA, NA, NA, NA, NA, NA, NA, NA,…
## $ `BUILDING CLASS AT PRESENT` <chr> "S1", "A5", "A5", "A9", "A9", "…
## $ ADDRESS <chr> "8684 15TH AVENUE", "14 BAY 10T…
## $ `APARTMENT NUMBER` <chr> NA, NA, NA, NA, NA, NA, NA, NA,…
## $ `ZIP CODE` <dbl> 11228, 11228, 11214, 11214, 112…
## $ `RESIDENTIAL UNITS` <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ `COMMERCIAL UNITS` <dbl> 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ `TOTAL UNITS` <dbl> 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ `LAND SQUARE FEET` <dbl> 1933, 2513, 2492, 1571, 2320, 3…
## $ `GROSS SQUARE FEET` <dbl> 4080, 1428, 972, 1456, 1566, 22…
## $ `YEAR BUILT` <dbl> 1930, 1930, 1950, 1935, 1930, 1…
## $ `TAX CLASS AT TIME OF SALE` <chr> "1", "1", "1", "1", "1", "1", "…
## $ `BUILDING CLASS AT TIME OF SALE` <chr> "S1", "A5", "A5", "A9", "A9", "…
## $ `SALE PRICE` <dbl> 1300000, 849000, 0, 830000, 0, …
## $ `SALE DATE` <dttm> 2020-04-28, 2020-03-18, 2019-0…

The glimpse() function provides a user-friendly way to view the column names and data types for all columns, or variables, in the data frame. With this function, we are also able to view the first few observations in the data frame. This data frame has 20,185 observations, or property sales records. And there are 21 variables, or columns.

#data science tutorials #beginner #r #r tutorial #r tutorials #rstats #tidyverse #tutorial #tutorials

Marcus  Flatley

Marcus Flatley

1594399440

Getting Started with R Markdown — Guide and Cheatsheet

In this blog post, we’ll look at how to use R Markdown. By the end, you’ll have the skills you need to produce a document or presentation using R Mardown, from scratch!

We’ll show you how to convert the default R Markdown document into a useful reference guide of your own. We encourage you to follow along by building out your own R Markdown guide, but if you prefer to just read along, that works, too!

R Markdown is an open-source tool for producing reproducible reports in R. It enables you to keep all of your code, results, plots, and writing in one place. R Markdown is particularly useful when you are producing a document for an audience that is interested in the results from your analysis, but not your code.

R Markdown is powerful because it can be used for data analysis and data science, collaborating with others, and communicating results to decision makers. With R Markdown, you have the option to export your work to numerous formats including PDF, Microsoft Word, a slideshow, or an HTML document for use in a website.

r markdown tips, tricks, and shortcuts

Turn your data analysis into pretty documents with R Markdown.

We’ll use the RStudio integrated development environment (IDE) to produce our R Markdown reference guide. If you’d like to learn more about RStudio, check out our list of 23 awesome RStudio tips and tricks!

Here at Dataquest, we love using R Markdown for coding in R and authoring content. In fact, we wrote this blog post in R Markdown! Also, learners on the Dataquest platform use R Markdown for completing their R projects.

We included fully-reproducible code examples in this blog post. When you’ve mastered the content in this post, check out our other blog post on R Markdown tips, tricks, and shortcuts.

Okay, let’s get started with building our very own R Markdown reference document!

R Markdown Guide and Cheatsheet: Quick Navigation

1. Install R Markdown

R Markdown is a free, open source tool that is installed like any other R package. Use the following command to install R Markdown:

install.packages("rmarkdown")

Now that R Markdown is installed, open a new R Markdown file in RStudio by navigating to File > New File > R Markdown…. R Markdown files have the file extension “.Rmd”.

2. Default Output Format

When you open a new R Markdown file in RStudio, a pop-up window appears that prompts you to select output format to use for the document.

New Document

The default output format is HTML. With HTML, you can easily view it in a web browser.

We recommend selecting the default HTML setting for now — it can save you time! Why? Because compiling an HTML document is generally faster than generating a PDF or other format. When you near a finished product, you change the output to the format of your choosing and then make the final touches.

One final thing to note is that the title you give your document in the pop-up above is not the file name! Navigate to File > Save As.. to name, and save, the document.

#data science tutorials #beginner #r #r markdown #r tutorial #r tutorials #rstats #rstudio #tutorial #tutorials

I am Developer

1617089618

Laravel 8 Tutorial for Beginners

Hello everyone! I just updated this tutorial for Laravel 8. In this tutorial, we’ll go through the basics of the Laravel framework by building a simple blogging system. Note that this tutorial is only for beginners who are interested in web development but don’t know where to start. Check it out if you are interested: Laravel Tutorial For Beginners

Laravel is a very powerful framework that follows the MVC structure. It is designed for web developers who need a simple, elegant yet powerful toolkit to build a fully-featured website.

Recommended:-Laravel Try Catch

#laravel 8 tutorial #laravel 8 tutorial crud #laravel 8 tutorial point #laravel 8 auth tutorial #laravel 8 project example #laravel 8 tutorial for beginners