How to Bundle a Simple Static Site Using Webpack

Webpack has established itself as an indispensable part of the JavaScript toolchain. It has over 55,000 stars on GitHub and is used by many of the big players in the JavaScript world, such as React and Angular.

However, you don’t need to be using a front-end framework, or be working on a large-scale project to take advantage of it. Webpack is primarily a bundler, and as such you can also use it to bundle just about any resource or asset you care to think of.

In this article, I’m going to show you how to install and configure webpack, then use it to create minified bundles for a simple static site with a handful of assets.

But Why Would You Want to Do That?

Good question. Glad you asked!

One of the reasons for doing this is to minimize the number of HTTP requests you make to the server. As the average web page grows, you’ll likely include jQuery (yes, it’s still popular in 2020), a couple of fonts, a few plugins, as well as various style sheets and some JavaScript of your own. If you’re making a network request for each of these assets, things soon add up and your page can become sluggish. Bundling your code can go some way to mitigating this problem.

Webpack also makes it easy to minify your code, further reducing its size, and it lets you write your assets in whatever flavor you desire. For example, in this article I’ll demonstrate how to have webpack transpile modern JavaScript to ES5. This means you can write JavaScript using the latest, most up-to-date syntax (although this might not be fully supported yet), then serve the browsers ES5 that will run almost everywhere.

And finally, it’s a fun learning exercise. Whether or not you employ any of these techniques in your own projects is down to you, but by following along you’ll get a firm understanding of what webpack does, how it does it and whether it’s a good fit for you.

Getting up and Running

The first thing you’ll need is to have Node and npm installed on your computer. If you haven’t got Node yet, you can either download it from the Node website, or you can download and install it with the aid of a version manager. Personally, I much prefer this second method, as it allows you to switch between multiple versions of Node and it negates a bunch of permissions errors, which might otherwise see you installing Node packages with admin rights.

We’ll also need a skeleton project to work with. Here’s one I made earlier. To get it running on your machine, you should clone the project from GitHub and install the dependencies:

git clone https://github.com/sitepoint-editors/webpack-static-site-example
cd webpack-static-site-example
npm install

This will install jQuery, plus Slick Slider and Lightbox2 — two plugins we’ll be using on the site — to a node_modules folder in the root of the project.

After that, you can open index.html in your browser and navigate the site. You should see something like this:

Our static site

If you need help with any of the steps above, why not head over to our forums and post a question.

Introducing Webpack to the Project

The next thing we’ll need to do is to install webpack. We can do this with the following command:

npm install webpack webpack-cli --save-dev

This will install webpack and the webpack CLI and add them to the devDependency section of your package.json file:

"devDependencies": {
  "webpack": "^5.1.3",
  "webpack-cli": "^4.0.0"
}

Next, we’ll make a dist folder which will contain our bundled JavaScript:

mkdir dist

Now we can try and run webpack from the command line to see if it is set up correctly:

./node_modules/webpack/bin/webpack.js ./src/js/main.js --output-filename=bundle.js --mode=development

What we’re doing here is telling webpack to bundle the contents of src/js/main.js into dist/bundle.js. If everything is installed correctly, you should see something like this output to the command line:

asset bundle.js 1.04 KiB [emitted] (name: main)
./src/js/main.js 192 bytes [built] [code generated]
webpack 5.1.3 compiled successfully in 45 ms

And webpack will create a bundle.js file in the dist folder. If you have a look at that file in your text editor of choice, you’ll see a bunch of boilerplate and the contents of main.js at the bottom.

Automating Our Setup

If we had to type all of the above into the terminal every time we wanted to run webpack, that’d be quite annoying. So let’s create an npm script we can run instead.

In package.json, alter the scripts property to look like this:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "build": "webpack ./src/js/main.js --output-filename=bundle.js --mode=development"
},

Notice how we can leave out the full path to the webpack module, as when run from a script, npm will automatically look for the module in the node_modules folder. Now when you run npm run build, the same thing should happen as before. Cool, eh?

Create a Webpack Configuration File

Notice how we’re passing the path of the file to bundle and the path of the output file as arguments to webpack? Well, we should probably change that and specify these in a configuration file instead. This will make our life easier when we come to use loaders later on.

Create a webpack.config.js file in the project root:

touch webpack.config.js

And add the following code:

module.exports = {
  entry: './src/js/main.js',
  mode: 'development',
  output: {
	path: `${__dirname}/dist`,
	filename: 'bundle.js',
  },
};

And change the npm script to the following:

"scripts": {
  ...
  "build": "webpack"
},

In webpack.config.js we’re exporting a configuration object, which specifies the entry point, the mode webpack should run in (more on that later), and the output location of the bundle. Run everything again and it should all still work as before.

Including the Bundle

Now that we have webpack generating a bundle for us, the next thing we need to do is to include it somewhere. But first, let’s create a different entry point, so that we can list the assets we want webpack to bundle for us. This will be a file named app.js in the src/js directory:

touch src/js/app.js

Add the following to app.js:

require('./main.js');

And change the webpack config thus:

entry: './src/js/app.js',

Run npm run build again to recreate the bundle. Everything should work as before.

Now, if you have a look at index.html you’ll notice that there’s not much going on JavaScript-wise. At the bottom of the file we are including jQuery and a file called main.js, which is responsible for showing more information when you click the Read more… link.

Let’s edit index.html to include the bundle instead of main.js. Look at the bottom of the file. You should see:

    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
	<script src="./src/js/main.js"></script>
  </body>
</html>

Change this to:

    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
	<script src="./dist/bundle.js"></script>
  </body>
</html>

Refresh the page in the browser and satisfy yourself that the Read more… link still works.

Bundling jQuery

Next, let’s add jQuery to the bundle. That will reduce the number of HTTP requests the page is making. To do this, we have to alter the app.js file like so:

window.$ = require('jquery');
require('./main.js');

Here we’re requiring jQuery, but as we installed this using npm, we don’t have to include the full path. We’re also adding its usual $ alias to the global window object, so that it’s accessible by other scripts. We’re requiring main.js after jQuery, as the former depends on the latter, and order is important.

Alter index.html to remove the jQuery script tag:

    <script src="./dist/bundle.js"></script>
  </body>
</html>

Run npm run build and once again, refresh the page in the browser to satisfy yourself that the Read more… link still works. It does? Good!

Measuring Our Progress

It’s all well and good to talk about performance, but it means very little if you don’t establish some kind of measurable metric. In our case, we’re attempting to reduce the number of HTTP requests the browser is making and we can view these from within the browser’s developer tools. I’ll use Chrome as an example of how to do this, but the principle is the same for any modern browser.

Press the F12 key to open the developer tools, then make sure the Network tab is selected. Then click and hold the reload symbol next to the address bar (the circle with an arrow) and select Empty Cache and Hard Reload. You should see something similar to the image below.

The Chrome developer tools displaying the number of network requests

As you can see in the bar at the bottom of the window, eight requests are being made (we’ve already shaved one off by adding jQuery to our bundle) and a total of 557kB are being transferred across the wire.

Bundling the CSS

Looking at index.html, the only other thing we’re making a network request for is the CSS. As you can see, we’re including main.css at the top of the page, and this file is, in turn, importing another four CSS files.

Although in its standard configuration webpack can only deal with JavaScript, we can use something called a loader to have it bundle our CSS, too. From the webpack docs:

Loaders are transformations that are applied to the source code of a module. They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules!

So let’s alter app.js:

// CSS
require('../css/main.css');

// JavaScript
window.$ = require('jquery');
require('./main.js');

And we need to alter webpack.config.js to tell it which loader to run when it encounters a file ending in .css:

module.exports = {
  ...
  module: {
	rules: [
	  {
		test: /\.css$/,
		use: [
		  'style-loader',
		  'css-loader',
		],
	  },
	],
  },
};

As you can see, I’ve specified two loaders: css-loader and style-loader. Of the two, css-loader transforms CSS to a JavaScript module, and style-loader injects the CSS that’s exported by the JavaScript module into a <style> tag at runtime. Let’s install both:

npm install --save-dev css-loader style-loader

Now let’s run webpack again using npm run build and see what happens:

> Webpack-static-site-example@1.0.0 build /home/jim/Downloads/webpack-static-site-example
> webpack

asset bundle.js 349 KiB [emitted] (name: main)
runtime modules 931 bytes 4 modules
modules by path ./src/ 356 KiB
  modules by path ./src/css/*.css 3.96 KiB 6 modules
  modules by path ./src/js/*.js 294 bytes
	./src/js/app.js 102 bytes [built] [code generated]
	./src/js/main.js 192 bytes [built] [code generated]
  ./src/fonts/open-sans/OpenSans-ExtraBold.ttf 352 KiB [built] [code generated] [1 error]
modules by path ./node_modules/ 290 KiB
  modules by path ./node_modules/css-loader/dist/runtime/*.js 2.38 KiB
	./node_modules/css-loader/dist/runtime/api.js 1.57 KiB [built] [code generated]
	./node_modules/css-loader/dist/runtime/getUrl.js 830 bytes [built] [code generated]
  ./node_modules/jquery/dist/jquery.js 281 KiB [built] [code generated]
  ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built] [code generated]

ERROR in ./src/fonts/open-sans/OpenSans-ExtraBold.ttf 1:0
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
 @ ./node_modules/css-loader/dist/cjs.js!./src/css/fonts.css 4:0-86 6:73-102
 @ ./node_modules/css-loader/dist/cjs.js!./src/css/main.css 3:0-104 8:26-59
 @ ./src/css/main.css 2:12-89 9:17-24 13:15-29
 @ ./src/js/app.js 2:0-26

webpack 5.1.3 compiled with 1 error in 292 ms

Oh noes! It blew up. Examining the output, it seems that there was an error in src/css/fonts.css. If you open that file and look at line 5, you’ll see that we’re including a custom font (src/fonts/open-sans/OpenSans-ExtraBold.ttf) and webpack doesn’t know what to do with it.

But don’t worry, we’ve got that! We just need to use another loader. This time it’s url-loader, which can convert assets such as fonts and images into data URLs, which can then be added to the bundle:

module.exports = {
  ...
  module: {
	rules: [
	  {
		test: /\.css$/,
		use: [
		  'style-loader',
		  'css-loader',
		],
	  },
	  {
		test: /\.ttf$/,
		use: [
		  'url-loader',
		],
	  },
	],
  },
};

And of course, we need to install it:

npm install url-loader --save-dev

Now the build should run. Test things out by removing the CSS <link> tag from index.html, recreating the bundle and refreshing the page.

#webpack #javascript #web-development #programming #developer

What is GEEK

Buddha Community

How to Bundle a Simple Static Site Using Webpack
Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

How to Bundle a Simple Static Site Using Webpack

Webpack has established itself as an indispensable part of the JavaScript toolchain. It has over 55,000 stars on GitHub and is used by many of the big players in the JavaScript world, such as React and Angular.

However, you don’t need to be using a front-end framework, or be working on a large-scale project to take advantage of it. Webpack is primarily a bundler, and as such you can also use it to bundle just about any resource or asset you care to think of.

In this article, I’m going to show you how to install and configure webpack, then use it to create minified bundles for a simple static site with a handful of assets.

But Why Would You Want to Do That?

Good question. Glad you asked!

One of the reasons for doing this is to minimize the number of HTTP requests you make to the server. As the average web page grows, you’ll likely include jQuery (yes, it’s still popular in 2020), a couple of fonts, a few plugins, as well as various style sheets and some JavaScript of your own. If you’re making a network request for each of these assets, things soon add up and your page can become sluggish. Bundling your code can go some way to mitigating this problem.

Webpack also makes it easy to minify your code, further reducing its size, and it lets you write your assets in whatever flavor you desire. For example, in this article I’ll demonstrate how to have webpack transpile modern JavaScript to ES5. This means you can write JavaScript using the latest, most up-to-date syntax (although this might not be fully supported yet), then serve the browsers ES5 that will run almost everywhere.

And finally, it’s a fun learning exercise. Whether or not you employ any of these techniques in your own projects is down to you, but by following along you’ll get a firm understanding of what webpack does, how it does it and whether it’s a good fit for you.

Getting up and Running

The first thing you’ll need is to have Node and npm installed on your computer. If you haven’t got Node yet, you can either download it from the Node website, or you can download and install it with the aid of a version manager. Personally, I much prefer this second method, as it allows you to switch between multiple versions of Node and it negates a bunch of permissions errors, which might otherwise see you installing Node packages with admin rights.

We’ll also need a skeleton project to work with. Here’s one I made earlier. To get it running on your machine, you should clone the project from GitHub and install the dependencies:

git clone https://github.com/sitepoint-editors/webpack-static-site-example
cd webpack-static-site-example
npm install

This will install jQuery, plus Slick Slider and Lightbox2 — two plugins we’ll be using on the site — to a node_modules folder in the root of the project.

After that, you can open index.html in your browser and navigate the site. You should see something like this:

Our static site

If you need help with any of the steps above, why not head over to our forums and post a question.

Introducing Webpack to the Project

The next thing we’ll need to do is to install webpack. We can do this with the following command:

npm install webpack webpack-cli --save-dev

This will install webpack and the webpack CLI and add them to the devDependency section of your package.json file:

"devDependencies": {
  "webpack": "^5.1.3",
  "webpack-cli": "^4.0.0"
}

Next, we’ll make a dist folder which will contain our bundled JavaScript:

mkdir dist

Now we can try and run webpack from the command line to see if it is set up correctly:

./node_modules/webpack/bin/webpack.js ./src/js/main.js --output-filename=bundle.js --mode=development

What we’re doing here is telling webpack to bundle the contents of src/js/main.js into dist/bundle.js. If everything is installed correctly, you should see something like this output to the command line:

asset bundle.js 1.04 KiB [emitted] (name: main)
./src/js/main.js 192 bytes [built] [code generated]
webpack 5.1.3 compiled successfully in 45 ms

And webpack will create a bundle.js file in the dist folder. If you have a look at that file in your text editor of choice, you’ll see a bunch of boilerplate and the contents of main.js at the bottom.

Automating Our Setup

If we had to type all of the above into the terminal every time we wanted to run webpack, that’d be quite annoying. So let’s create an npm script we can run instead.

In package.json, alter the scripts property to look like this:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "build": "webpack ./src/js/main.js --output-filename=bundle.js --mode=development"
},

Notice how we can leave out the full path to the webpack module, as when run from a script, npm will automatically look for the module in the node_modules folder. Now when you run npm run build, the same thing should happen as before. Cool, eh?

Create a Webpack Configuration File

Notice how we’re passing the path of the file to bundle and the path of the output file as arguments to webpack? Well, we should probably change that and specify these in a configuration file instead. This will make our life easier when we come to use loaders later on.

Create a webpack.config.js file in the project root:

touch webpack.config.js

And add the following code:

module.exports = {
  entry: './src/js/main.js',
  mode: 'development',
  output: {
	path: `${__dirname}/dist`,
	filename: 'bundle.js',
  },
};

And change the npm script to the following:

"scripts": {
  ...
  "build": "webpack"
},

In webpack.config.js we’re exporting a configuration object, which specifies the entry point, the mode webpack should run in (more on that later), and the output location of the bundle. Run everything again and it should all still work as before.

Including the Bundle

Now that we have webpack generating a bundle for us, the next thing we need to do is to include it somewhere. But first, let’s create a different entry point, so that we can list the assets we want webpack to bundle for us. This will be a file named app.js in the src/js directory:

touch src/js/app.js

Add the following to app.js:

require('./main.js');

And change the webpack config thus:

entry: './src/js/app.js',

Run npm run build again to recreate the bundle. Everything should work as before.

Now, if you have a look at index.html you’ll notice that there’s not much going on JavaScript-wise. At the bottom of the file we are including jQuery and a file called main.js, which is responsible for showing more information when you click the Read more… link.

Let’s edit index.html to include the bundle instead of main.js. Look at the bottom of the file. You should see:

    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
	<script src="./src/js/main.js"></script>
  </body>
</html>

Change this to:

    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
	<script src="./dist/bundle.js"></script>
  </body>
</html>

Refresh the page in the browser and satisfy yourself that the Read more… link still works.

Bundling jQuery

Next, let’s add jQuery to the bundle. That will reduce the number of HTTP requests the page is making. To do this, we have to alter the app.js file like so:

window.$ = require('jquery');
require('./main.js');

Here we’re requiring jQuery, but as we installed this using npm, we don’t have to include the full path. We’re also adding its usual $ alias to the global window object, so that it’s accessible by other scripts. We’re requiring main.js after jQuery, as the former depends on the latter, and order is important.

Alter index.html to remove the jQuery script tag:

    <script src="./dist/bundle.js"></script>
  </body>
</html>

Run npm run build and once again, refresh the page in the browser to satisfy yourself that the Read more… link still works. It does? Good!

Measuring Our Progress

It’s all well and good to talk about performance, but it means very little if you don’t establish some kind of measurable metric. In our case, we’re attempting to reduce the number of HTTP requests the browser is making and we can view these from within the browser’s developer tools. I’ll use Chrome as an example of how to do this, but the principle is the same for any modern browser.

Press the F12 key to open the developer tools, then make sure the Network tab is selected. Then click and hold the reload symbol next to the address bar (the circle with an arrow) and select Empty Cache and Hard Reload. You should see something similar to the image below.

The Chrome developer tools displaying the number of network requests

As you can see in the bar at the bottom of the window, eight requests are being made (we’ve already shaved one off by adding jQuery to our bundle) and a total of 557kB are being transferred across the wire.

Bundling the CSS

Looking at index.html, the only other thing we’re making a network request for is the CSS. As you can see, we’re including main.css at the top of the page, and this file is, in turn, importing another four CSS files.

Although in its standard configuration webpack can only deal with JavaScript, we can use something called a loader to have it bundle our CSS, too. From the webpack docs:

Loaders are transformations that are applied to the source code of a module. They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules!

So let’s alter app.js:

// CSS
require('../css/main.css');

// JavaScript
window.$ = require('jquery');
require('./main.js');

And we need to alter webpack.config.js to tell it which loader to run when it encounters a file ending in .css:

module.exports = {
  ...
  module: {
	rules: [
	  {
		test: /\.css$/,
		use: [
		  'style-loader',
		  'css-loader',
		],
	  },
	],
  },
};

As you can see, I’ve specified two loaders: css-loader and style-loader. Of the two, css-loader transforms CSS to a JavaScript module, and style-loader injects the CSS that’s exported by the JavaScript module into a <style> tag at runtime. Let’s install both:

npm install --save-dev css-loader style-loader

Now let’s run webpack again using npm run build and see what happens:

> Webpack-static-site-example@1.0.0 build /home/jim/Downloads/webpack-static-site-example
> webpack

asset bundle.js 349 KiB [emitted] (name: main)
runtime modules 931 bytes 4 modules
modules by path ./src/ 356 KiB
  modules by path ./src/css/*.css 3.96 KiB 6 modules
  modules by path ./src/js/*.js 294 bytes
	./src/js/app.js 102 bytes [built] [code generated]
	./src/js/main.js 192 bytes [built] [code generated]
  ./src/fonts/open-sans/OpenSans-ExtraBold.ttf 352 KiB [built] [code generated] [1 error]
modules by path ./node_modules/ 290 KiB
  modules by path ./node_modules/css-loader/dist/runtime/*.js 2.38 KiB
	./node_modules/css-loader/dist/runtime/api.js 1.57 KiB [built] [code generated]
	./node_modules/css-loader/dist/runtime/getUrl.js 830 bytes [built] [code generated]
  ./node_modules/jquery/dist/jquery.js 281 KiB [built] [code generated]
  ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built] [code generated]

ERROR in ./src/fonts/open-sans/OpenSans-ExtraBold.ttf 1:0
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
 @ ./node_modules/css-loader/dist/cjs.js!./src/css/fonts.css 4:0-86 6:73-102
 @ ./node_modules/css-loader/dist/cjs.js!./src/css/main.css 3:0-104 8:26-59
 @ ./src/css/main.css 2:12-89 9:17-24 13:15-29
 @ ./src/js/app.js 2:0-26

webpack 5.1.3 compiled with 1 error in 292 ms

Oh noes! It blew up. Examining the output, it seems that there was an error in src/css/fonts.css. If you open that file and look at line 5, you’ll see that we’re including a custom font (src/fonts/open-sans/OpenSans-ExtraBold.ttf) and webpack doesn’t know what to do with it.

But don’t worry, we’ve got that! We just need to use another loader. This time it’s url-loader, which can convert assets such as fonts and images into data URLs, which can then be added to the bundle:

module.exports = {
  ...
  module: {
	rules: [
	  {
		test: /\.css$/,
		use: [
		  'style-loader',
		  'css-loader',
		],
	  },
	  {
		test: /\.ttf$/,
		use: [
		  'url-loader',
		],
	  },
	],
  },
};

And of course, we need to install it:

npm install url-loader --save-dev

Now the build should run. Test things out by removing the CSS <link> tag from index.html, recreating the bundle and refreshing the page.

#webpack #javascript #web-development #programming #developer

Ahebwe  Oscar

Ahebwe Oscar

1623192840

Does My Site Work?

EPISODE SUMMARY

On this episode, we will discuss how you can verify that your site works and continues to work. We’re digging into automated testing and how to write tests for your Django apps.

Full show notes are available at https://www.mattlayman.com/django-riffs/13.

EPISODE NOTES

Full show notes are available at https://www.mattlayman.com/django-riffs/13.

#does my site work? #your site is #episode summary #episode notes #the site. #my site work

Vincent Lab

Vincent Lab

1605177550

Building a Static Website with Hugo

#hugo #static #site #generator #markup #static site generator