search
HomeWeb Front-endJS TutorialWebpack Getting Started Tutorial
Webpack Getting Started TutorialSep 23, 2019 am 11:35 AM
webpack

Webpack is a front-end resource loading/packaging tool. It will perform static analysis based on module dependencies, and then generate corresponding static resources for these modules according to specified rules.

This chapter is based on Webpack3.0 and passed the test.

Webpack Getting Started Tutorial

We can see from the picture that Webpack can convert a variety of static resources js, css, and less into a static file, reducing page requests.

Next we will briefly introduce the installation and use of Webpack.

Install Webpack

Before installing Webpack, your local environment needs to support node.js.

Due to the slow installation speed of npm, this tutorial uses Taobao's image and its command cnpm. For installation and usage instructions, please refer to: Using Taobao NPM image.

Use cnpm to install webpack:

cnpm install webpack -g

Create project

Next we create a directory app:

mkdir app

Add the runoob1.js file in the app directory, the code is as follows:

document.write("It works.");

Add the index.html file in the app directory, the code is as follows:

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script type="text/javascript" src="bundle.js" charset="utf-8"></script>
    </body>
</html>

Next we use the webpack command to Packaging:

webpack runoob1.js bundle.js

Executing the above command will compile the runoob1.js file and generate the bundle.js file. After success, the output information is as follows:

Hash: a41c6217554e666594cb
Version: webpack 1.12.13
Time: 50ms
    Asset     Size  Chunks             Chunk Names
bundle.js  1.42 kB       0  [emitted]  main
   [0] ./runoob1.js 29 bytes {0} [built]

Open index.html in the browser and output The results are as follows:

Webpack Getting Started Tutorial

Create a second JS file

Next we create another js file runoob2.js, the code is as follows:

module.exports = "It works from runoob2.js.";

Update the runoob1.js file, the code is as follows:

document.write(require("./runoob2.js"));

Next we use the webpack command to package:

webpack runoob1.js bundle.js
 
Hash: dcf55acff639ebfe1677
Version: webpack 1.12.13
Time: 52ms
    Asset     Size  Chunks             Chunk Names
bundle.js  1.55 kB       0  [emitted]  main
   [0] ./runoob1.js 41 bytes {0} [built]
   [1] ./runoob2.js 46 bytes {0} [built]

In browsing The output result is as follows:

Webpack Getting Started Tutorial

webpack performs static analysis based on the dependencies of the module, and these files (modules) will be included in the bundle.js file. Webpack assigns each module a unique id and indexes and accesses the module through this id. When the page starts, the code in runoob1.js will be executed first, and other modules will be executed when require is run.


LOADER

Webpack itself can only process JavaScript modules. If you want to process other types of files, you need to use loader for conversion. .

So if we need to add a css file to the application, we need to use css-loader and style-loader. They do two different things. The css-loader will traverse the CSS file and then find the url() Expressions are then processed and the style-loader inserts the original CSS code into a style tag on the page.

Next we use the following commands to install css-loader and style-loader (global installation requires parameter -g).

cnpm install css-loader style-loader

After executing the above command, the node_modules directory will be generated in the current directory, which is the installation directory of css-loader and style-loader.

Next create a style.css file, the code is as follows:

body {
    background: yellow;
}

Modify the runoob1.js file, the code is as follows:

require("!style-loader!css-loader!./style.css");
document.write(require("./runoob2.js"));

Next we use the webpack command to package:

webpack runoob1.js bundle.js
 
Hash: a9ef45165f81c89a4363
Version: webpack 1.12.13
Time: 619ms
    Asset     Size  Chunks             Chunk Names
bundle.js  11.8 kB       0  [emitted]  main
   [0] ./runoob1.js 76 bytes {0} [built]
   [5] ./runoob2.js 46 bytes {0} [built]
    + 4 hidden modules

When accessed in the browser, the output result is as follows:

Webpack Getting Started Tutorial

require CSS files must be written with the loader prefix!style-loader!css- loader!, of course we can automatically bind the required loader according to the module type (extension). Change require("!style-loader!css-loader!./style.css") in runoob1.js to require("./style.css"):

runoob1.js File

require("./style.css");
document.write(require("./runoob2.js"));

Then execute:

webpack runoob1.js bundle.js --module-bind &#39;css=style-loader!css-loader&#39;

Access in the browser, the output result is as follows:

Webpack Getting Started Tutorial

Obviously, this The two ways of using loader have the same effect.


Configuration file

We can put some compilation options in the configuration file for unified management:

Create the webpack.config.js file, the code is as follows:

module.exports = {
    entry: "./runoob1.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" }
        ]
    }
};

Next we only need to execute the webpack command to generate the bundle.js file:

webpack
 
Hash: 4fdefac099a5f36ff74b
Version: webpack 1.12.13
Time: 576ms
    Asset     Size  Chunks             Chunk Names
bundle.js  11.8 kB       0  [emitted]  main
   [0] ./runoob1.js 65 bytes {0} [built]
   [5] ./runoob2.js 46 bytes {0} [built]
    + 4 hidden modules

webpack command After execution, the webpack.config.js file in the current directory will be loaded by default.


Plug-ins

Plug-ins are specified in the plugins option of webpack's configuration information and are used to complete some tasks that cannot be completed by the loader.

Webpack comes with some plug-ins, and you can install some plug-ins through cnpm.

使用内置插件需要通过以下命令来安装:

cnpm install webpack --save-dev

比如我们可以安装内置的 BannerPlugin 插件,用于在文件头部输出一些注释信息。

修改 webpack.config.js,代码如下:

var webpack=require(&#39;webpack&#39;);
 
module.exports = {
    entry: "./runoob1.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" }
        ]
    },
    plugins:[
    new webpack.BannerPlugin(&#39;菜鸟教程 webpack 实例&#39;)
    ]
};

然后运行:

webpack

打开 bundle.js,可以看到文件头部出现了我们指定的注释信息。


开发环境

当项目逐渐变大,webpack 的编译时间会变长,可以通过参数让编译的输出内容带有进度和颜色。

webpack --progress --colors

如果不想每次修改模块后都重新编译,那么可以启动监听模式。开启监听模式后,没有变化的模块会在编译后缓存到内存中,而不会每次都被重新编译,所以监听模式的整体速度是很快的。

webpack --progress --colors --watch

当然,我们可以使用 webpack-dev-server 开发服务,这样我们就能通过 localhost:8080 启动一个 express 静态资源 web 服务器,并且会以监听模式自动运行 webpack,在浏览器打开 http://localhost:8080/ 或 http://localhost:8080/webpack-dev-server/ 可以浏览项目中的页面和编译后的资源输出,并且通过一个 socket.io 服务实时监听它们的变化并自动刷新页面。

# 安装
cnpm install webpack-dev-server -g
 
# 运行
webpack-dev-server --progress --colors

在浏览器打开 http://localhost:8080/ 输出结果如下:

Webpack Getting Started Tutorial

相关教程推荐:webpack 中文文档

The above is the detailed content of Webpack Getting Started Tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:runoob. If there is any infringement, please contact admin@php.cn delete
VUE3入门教程:使用Webpack进行打包和构建VUE3入门教程:使用Webpack进行打包和构建Jun 15, 2023 pm 06:17 PM

Vue是一款优秀的JavaScript框架,它可以帮助我们快速构建交互性强、高效性好的Web应用程序。Vue3是Vue的最新版本,它引入了很多新的特性和功能。Webpack是目前最流行的JavaScript模块打包器和构建工具之一,它可以帮助我们管理项目中的各种资源。本文就为大家介绍如何使用Webpack打包和构建Vue3应用程序。1.安装Webpack

vite和webpack的区别是什么vite和webpack的区别是什么Jan 11, 2023 pm 02:55 PM

区别:1、webpack服务器启动速度比vite慢;由于vite启动的时候不需要打包,也就无需分析模块依赖、编译,所以启动速度非常快。2、vite热更新比webpack快;vite在HRM方面,当某个模块内容改变时,让浏览器去重新请求该模块即可。3、vite用esbuild预构建依赖,而webpack基于node。4、vite的生态不及webpack,加载器、插件不够丰富。

如何使用PHP和webpack进行模块化开发如何使用PHP和webpack进行模块化开发May 11, 2023 pm 03:52 PM

随着Web开发技术的不断发展,前后端分离、模块化开发已经成为了一个广泛的趋势。PHP作为一种常用的后端语言,在进行模块化开发时,我们需要借助一些工具来实现模块的管理和打包,其中webpack是一个非常好用的模块化打包工具。本文将介绍如何使用PHP和webpack进行模块化开发。一、什么是模块化开发模块化开发是指将程序分解成不同的独立模块,每个模块都有自己的作

vue webpack可打包哪些文件vue webpack可打包哪些文件Dec 20, 2022 pm 07:44 PM

在vue中,webpack可以将js、css、图片、json等文件打包为合适的格式,以供浏览器使用;在webpack中js、css、图片、json等文件类型都可以被当做模块来使用。webpack中各种模块资源可打包合并成一个或多个包,并且在打包的过程中,可以对资源进行处理,如压缩图片、将scss转成css、将ES6语法转成ES5等可以被html识别的文件类型。

Webpack是什么?详解它是如何工作的?Webpack是什么?详解它是如何工作的?Oct 13, 2022 pm 07:36 PM

Webpack是一款模块打包工具。它为不同的依赖创建模块,将其整体打包成可管理的输出文件。这一点对于单页面应用(如今Web应用的事实标准)来说特别有用。

webpack怎么将es6转成es5的模块webpack怎么将es6转成es5的模块Oct 18, 2022 pm 03:48 PM

配置方法:1、用导入的方法把ES6代码放到打包的js代码文件中;2、利用npm工具安装babel-loader工具,语法“npm install -D babel-loader @babel/core @babel/preset-env”;3、创建babel工具的配置文件“.babelrc”并设定转码规则;4、在webpack.config.js文件中配置打包规则即可。

使用Spring Boot和Webpack构建前端工程和插件系统使用Spring Boot和Webpack构建前端工程和插件系统Jun 22, 2023 am 09:13 AM

随着现代Web应用程序的复杂性不断增加,构建优秀的前端工程和插件系统变得越来越重要。随着SpringBoot和Webpack的流行,它们成为了一个构建前端工程和插件系统的完美组合。SpringBoot是一个Java框架,它以最小的配置要求来创建Java应用程序。它提供了很多有用的功能,比如自动配置,使开发人员可以更快、更容易地搭建和部署Web应用程序。W

webpack处理css浏览器兼容性问题webpack处理css浏览器兼容性问题Aug 09, 2022 pm 02:50 PM

本篇文章给大家带来了关于javascript的相关知识,其中主要介绍了关于webpack处理css浏览器兼容性的相关问题,包括了postcss-loader和postcss-preset-env插件使用的相关内容,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),