search
HomeWeb Front-endJS TutorialWebpack Getting Started Tutorial

Webpack Getting Started Tutorial

Sep 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
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

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),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!