Home  >  Article  >  Web Front-end  >  webpack--detailed explanation of module packager

webpack--detailed explanation of module packager

零下一度
零下一度Original
2017-06-26 09:48:371972browse

Previous words

Before the emergence of webpack, the module management and packaging tools that already existed on the market were not suitable for large projects, especially single-page web applications. The most pressing reason is how to maintain the division and storage of various module resources in a large-scale code base, maintain the dependencies between them, and seamlessly integrate them together to generate content suitable for browser-side request loading. Static resources. Webpack is currently the most popular modular management and packaging tool for front-end resources. It can package many loose modules into front-end resources that are consistent with production environment deployment according to dependencies and rules. You can also code-separate the modules loaded on demand, and then load them asynchronously when actually needed

Webpack is rich and messy in content, which is not friendly to novices. This article uses an example to introduce the important concepts of webpack, and focuses on how to use webpack

Overview

Webpack is a module packager.

【Features】

Webpack has the following features

Code splitting

Webpack has two ways to organize module dependencies, Synchronous and asynchronous. Asynchronous dependencies serve as split points to form a new block. After optimizing the dependency tree, each asynchronous block is packaged as a file.

Loader

Webpack itself can only handle native JavaScript modules, but the loader converter can convert various types of resources into JavaScript modules. This way, any resource can become a module that Webpack can handle.

Smart parsing

Webpack has a smart parser that can handle almost any third-party library, whether they are modules in the form of CommonJS, AMD, or ordinary JS files. Even when loading dependencies, the dynamic expression require("./templates/" + name + ".jade") is allowed.

Plug-in system

Webpack also has a feature-rich plug-in system. Most content functions run based on this plug-in system, and open source Webpack plug-ins can also be developed and used to meet a variety of needs.

Run quickly

Webpack uses asynchronous I/O and multi-level caching to improve running efficiency, which allows Webpack to compile incrementally at incredibly fast speeds

【Installation】

Use npm to install Webpack

$ npm install webpack

A common problem is: after installing webpack, the webpack command cannot be used

This is because only local installation is performed, not global installation. Enter the following code to perform global installation and then run it

$ npm install webpack -g

Use

First create a static page index.html and a JS entry file entry.js

<!-- index.html -->
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <script src="bundle.js?1.1.11"></script>
</body>
</html>
// entry.jsdocument.write('It works.')

Then compile entry.js and package it into bundle.js:

$ webpack entry.js bundle.js

The packaging process will display the log:

Hash: f47511e706e3de8f2417
Version: webpack 2.6.1Time: 47ms
    Asset     Size  Chunks             Chunk Names
bundle.js  2.66 kB       0  [emitted]  main
   [0] ./entry.js 27 bytes {0} [built]

Open index.html with a browser and you will see It works.

Next, add a module module.js and modify the entry entry.js:

// module.jsmodule.exports = 'It works from module.js.'
// entry.jsdocument.write('It works.')
document.write(require('./module.js')) // 添加模块

Repackage webpack entry.js bundle.js Refresh the page to see the changes It works.It works from module. js.

Hash: 09733456f2c5b24a4845
Version: webpack 2.6.1Time: 61ms
    Asset     Size  Chunks             Chunk Names
bundle.js  2.83 kB       0  [emitted]  main
   [0] ./module.js 43 bytes {0} [built]
   [1] ./entry.js 75 bytes {0} [built]

Webpack will analyze the entry file and parse each file containing dependencies. These files (modules) are bundled into bundle.js. Webpack assigns each module a unique id and indexes and accesses the module through this id. When the page starts, the code in entry.js will be executed first, and other modules will be executed

Loader

when running

require

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

Loader can be understood as a converter for modules and resources. It itself is a function that accepts source files as parameters and returns the conversion result. Detailed information moves here

Following the above example, we need to introduce a CSS file style.css into the page. To use require("!style-loader!css-loader!./style.css?1.1 .11") code, the code reading order is from right to left, which means that the homepage regards style.css as a module, loads style.css first, and then uses css-loader to read it, Then use style-loader to insert it into the page

/* style.css */body { background: yellow; }

Modify entry.js:

require("style-loader!css-loader!./style.css?1.1.11") 
document.write('It works.')
document.write(require('./module.js'))

Install loader :

npm install css-loader style-loader

  重新编译打包,刷新页面,就可以看到黄色的页面背景了

  如果每次 require CSS 文件的时候都要写 loader 前缀,是一件很繁琐的事情。我们可以根据模块类型(扩展名)来自动绑定需要的 loader。

  将 entry.js 中的 require("!style-loader!css-loader!./style.css?1.1.11") 修改为 require("./style.css?1.1.11") ,然后执行

$ webpack entry.js bundle.js --module-bind 'css=style-loader!css-loader'

  显然,这两种使用 loader 的方式,效果是一样的

 

配置

  Webpack 在执行的时候,除了在命令行传入参数,还可以通过指定的配置文件来执行。默认情况下,会搜索当前目录的 webpack.config.js 文件,这个文件是一个 node.js 模块,返回一个 json 格式的配置信息对象,或者通过 --config选项来指定配置文件。

  继续我们的案例,在根目录创建 package.json 来添加 webpack 需要的依赖:

{  "name": "project",  "version": "1.0.0",  "devDependencies": {"css-loader": "^0.28.4","style-loader": "^0.18.2","webpack": "^2.6.1"
  }
}

  别忘了运行 npm install。然后创建一个配置文件 webpack.config.js,在下面的配置中,对一个单独的module对象定义了rules属性,里面包含两个必须属性:test和use。相当于告诉webpack compiler,碰到「在require()/import语句中被解析为'.css'的路径」时,在把它们添加并打包之前,要先使用css-loader后使用style-loader去转换

var webpack = require('webpack');
module.exports = {
  entry: './entry.js', //入口文件  output: {
    path: __dirname,//出口路径filename: 'bundle.js'//出口名称  },
  module: {
    rules: [
      {test: /\.css$/,use: [ 'style-loader', 'css-loader' ]}
    ]
  }
}

  同时简化 entry.js 中的 style.css 加载方式:

require('./style.css');

  最后运行 webpack,可以看到 webpack 通过配置文件执行的结果和上一节通过命令行 webpack entry.js bundle.js --module-bind 'css=style!css' 执行的结果是一样的

  如果配置文件并不叫做默认的webpack.config.js,而是其他的名称,如test.js,则需要设置如下命令进行打包

webpack --config test.js

 

插件

  插件可以完成更多 loader 不能完成的功能。插件的使用一般是在 webpack 的配置信息 plugins 选项中指定。Webpack 本身内置了一些常用的插件,还可以通过 npm 安装第三方插件。详细信息移步至此

  想要使用一个插件,只需要require()它,然后把它添加到plugins数组中。内置插件则不需要require,直接使用即可

  接下来,我们利用一个最简单的 BannerPlugin 内置插件来实践插件的配置和运行,这个插件的作用是给输出的文件头部添加注释信息。

  修改 webpack.config.js,添加 plugins

var webpack = require('webpack');
module.exports = {
  entry: './entry.js', //入口文件  output: {
    path: __dirname,//出口路径filename: 'bundle.js'//出口名称  },
  module: {
    rules: [
      {test: /\.css$/,use: [ 'style-loader', 'css-loader' ]}
    ]
  },
  plugins: [new webpack.BannerPlugin('This file is created by xiaohuochai')
  ]
}

  然后运行 webpack,打开 bundle.js,可以看到文件头部出现了我们指定的注释信息:

/*! This file is created by xiaohuochai *//******/ (function(modules) { // webpackBootstrap/******/  // The module cache/******/  var installedModules = {};// 后面代码省略

 

开发环境

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

$ webpack --progress --colors

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

$ webpack --progress --colors --watch

  比如,执行以上命令后,修改'style.css'的body的背景颜色为红色,不用重新编译,刷新页面后,页面即发生改变

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

# 安装
$ npm install webpack-dev-server -g

# 运行
$ webpack-dev-server --progress --colors

  比如,执行以上命令后,修改'style.css'的body的背景颜色为蓝色,不用重新编译,也不用刷新页面,页面即发生改变

 

The above is the detailed content of webpack--detailed explanation of module packager. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn