Home >Web Front-end >JS Tutorial >Webpack Getting Started Tutorial

Webpack Getting Started Tutorial

PHPz
PHPzforward
2019-09-23 11:35:363099browse

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.com. If there is any infringement, please contact admin@php.cn delete