Home >Web Front-end >JS Tutorial >Detailed explanation of four basic concepts in webpack

Detailed explanation of four basic concepts in webpack

零下一度
零下一度Original
2017-06-26 09:46:081995browse

Previous words

Webpack is currently the most popular front-end resource modular management and packaging tool. It can package many loose modules into front-end resources that are consistent with production environment deployment according to dependencies and rules. When webpack processes an application, it recursively builds a dependency graph that contains every module the application needs, and then packages all these modules into a small number of bundles (usually just one), which are used by the browser. load. It is highly configurable, and you need to understand four core concepts before starting: entry, output, loader, and plug-ins. This article will introduce these four basic concepts of webpack in detail

Entry

Webpack will create a dependency graph for all applications. The starting point of the chart is called the entry point. The entry point tells webpack where to start and follows the dependency graph on what to bundle. The entry point of the application can be considered as the root context or the first startup file of the app

Analogous to the entry file main.js in requirejs, when it is finally packaged using r.js, it is packaged in main.js

In webpack, use the entry attribute in the webpack configuration object to define the entry, including the following methods

[Single entry (abbreviation) syntax]

Usage: entry : string|Array

 [Note] When setting the entry attribute, if it is the current page, be sure to set it to './' in front of the attribute value, otherwise it will not be recognized

//webpack.config.jsvar config = {
  entry: './path/to/my/entry/file.js'};

The single entry syntax of the entry attribute is the following abbreviation:

//webpack.config.jsvar config = {
  entry: {
    main: './path/to/my/entry/file.js'
  }
};

When an array is passed to entry, "multi-main" will be created entry)"

entry:['./entry1','./entry2']

【Object syntax】

Usage: entry: {[entryChunkName: string]: string|Array}

//webpack.config.jsvar config = {
  entry: {
    app: './src/app.js',
    vendors: './src/vendors.js'
  }
};

 Object syntax will be more cumbersome. However, this is the most scalable way to define entry points in your application

As you can see from the above code, webpack creates the dependency graph starting from app.js and vendors.js. These charts are completely separate and independent of each other. This method is more common in single page applications with only one entry point (excluding vendor)

Exit

After the assets are grouped together, you still need to tell webpack where to package the application. The output attribute of webpack describes how to handle bundled code

//webpack.config.jsvar path = require('path');
module.exports = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  }
};

In the above code, we tell webpack through the output.filename and output.path properties. The name of the bundle, and where we want to generate (emit) it

[Note] Even if there can be multiple entry points, only one output configuration is specified. As shown below, the filename of output must be [name] or It is similar, it cannot be a certain name, otherwise it will prompt Conflict: Multiple assets emit to the same filename bundle.js, which translates to multiple entries cannot specify the same filename in the export file

  entry: {'main': './entry.js','hello':'./hello.js'
  },
  output: {
    path: __dirname,//出口路径filename: '[name].js'//出口名称
  }

 

【Usage】

To configure the output attribute in webpack, you need to set its value to an object and include the two required options of filename and path attributes

Filename: The file name of the compiled file, the first recommendation is: //main.js||bundle.js||index.js

Path: Corresponds to an absolute path, this path is expected to be packaged at one time Directory

 config ='bundle.js''/home/proj/public/assets'

【Options】

output.chunkFilename

Non-entry chunk(non-entry chunk), the path is relative to the output.path directory

[id] 被chunk的id替换
[name] 被chunk的name替换(或者,在chunk没有name时使用id替换)
[hash] 被compilation生命周期的hash替换
[chunkhash] 被chunk的hash替换

output.crossOriginLoading

This option enables cross-origin loading (cross -origin loading)chunk, optional values ​​are:

false - 禁用跨域加载(默认值)"anonymous" - 启用跨域加载。当使用 anonymous 时,发送不带凭据(credential)的请求。"use-credentials" - 启用跨域加载。发送带凭据(credential)的请求

output.devtoolLineToLine

All/specified modules enable line-to-line mapping ( line-to-line mapped) mode. Row-to-row mapping mode uses a simple SourceMap, that is, each row of the generated source is mapped to the same row of the original source. This is an area where performance optimization can be done. Only consider enabling

<span style="color: #0000ff;">true</span><span style="color: #000000;"> 在所有模块启用(不推荐)
{test, include, exclude} 对象,对特定文件启用(类似于 module.loaders)<br>默认值:</span><span style="color: #0000ff;">false</span>

output.filename# when better performance is required and only if the input line and generated line match.

##Specify the name of each output file on the hard disk. An absolute path cannot be specified here. The output.path option specifies the location on the hard disk where the file is written. filename is only used to name each file

//单个入口{
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: __dirname + '/build'
  }
}
//多个入口{
  entry: {
    app: './src/app.js',
    search: './src/search.js'
  },
  output: {
    filename: '[name].js',//被 chunk 的 name 替换path: __dirname + '/build'
  }
}

output.hotUpdateChunkFilename

Hot Update Chunk ) file name. They are in the output.path directory

[id] 被chunk的id替换
[hash] 被compilation生命周期的hash替换。(最后一个hash存储在记录中)
默认值:"[id].[hash].hot-update.js?1.1.11"

output.hotUpdateFunction

Used in webpack for asynchronous load (async load) hot update (hot update) )chunk’s JSONP function

默认值:"webpackHotUpdate"

output.hotUpdateMainFilename

  热更新主文件(hot update main file)的文件名

[hash] 被compilation生命周期的hash替换。(最后一个hash存储在记录中)
默认值:"[hash].hot-update.json"

output.jsonpFunction

  webpack中用于异步加载(async loading)chunk的JSONP函数

  较短的函数可能会减少文件大小。当单页有多个webpack实例时,请使用不同的标识符(identifier)

默认值:"webpackJsonp"

output.library

  如果设置此选项,会将bundle导出为library。output.library是library的名称。

  如果正在编写library,并且需要将其发布为单独的文件,请使用此选项

output.libraryTarget

  library的导出格式

"var" - 导出为一个变量: Library ="this" - 导出为  的一个属性:["Library"] ="commonjs" - 导出为 exports 的一个属性:exports["Library"] ="commonjs2" - 通过 module.exports:module.exports ="amd" - 导出为 AMD(可选命名 -"umd" -

  如果output.library未设置,但是output.libraryTarget被设置为var以外的值,则「所导出对象」的每个属性都被复制到「对应的被导出对象」上(除了amd,commonjs2和umd)

output.publicPath

  一般地,publicPath用于设置上线地址,在开发过程中,该值不需要设置

output: {
    filename:'main.js'path: "/home/proj/public/assets",
    publicPath: "http://cdn.com"}

  以上面代码为例,最终main.js的线上地址是'http://cdn.com/home/proj/public/assets/main.js'

output.path

  导出目录为绝对路径(必选项)

//config.jsoutput: {
    path: "/home/proj/public/assets",
    publicPath: "/assets/"}//index.html<head>
  <link href="/assets/spinner.gif"/>
</head>
//config.jsoutput: {
    path: "/home/proj/cdn/assets/[hash]",
    publicPath: "http://cdn.example.com/assets/[hash]/"}

  [注意]在编译时不知道最终输出文件的 publicPath 的情况下,publicPath 可以留空,并且在入口起点文件运行时动态设置。如果你在编译时不知道 publicPath,你可以先忽略它,并且在入口起点设置 __webpack_public_path__

 __webpack_public_path__ = myRuntimePublicPath

output.sourceMapFilename

  JavaScript 文件的 SourceMap 的文件名

[file] 被 JavaScript 文件的文件名替换
默认值:"[file].map"

 

加载器

  webpack的目标是,让webpack聚焦于项目中的所有资源(asset),而浏览器不需要关注考虑这些。webpack把每个文件(.css,.html,.scss,.jpg,etc.)都作为模块处理。然而webpack只理解JavaScript。webpack loader会将这些文件转换为模块,而转换后的文件会被添加到依赖图表中

  loader可以使你在require()或"加载"模块时预处理文件。因此,loader类似于其他构建工具中“任务(task)”,并提供了处理前端构建步骤的强大方法

  webpack的配置要能识别出(identify)应该被对应的loader进行转换(transform)的那些文件。由于进行过文件转换,所以能够将被转换的文件添加到依赖图表(并且最终添加到bundle中)(use属性)

var path = require('path');var config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      {test: /\.(js|jsx)$/, use: 'babel-loader'}
    ]
  }
};
module.exports = config;

  以上配置中,对一个单独的module对象定义了rules属性,里面包含两个必须属性:test和use。相当于告诉webpack compiler,碰到「在require()/import语句中被解析为'.js'或'.jsx'的路径」时,在把它们添加并打包之前,要先使用babel-loader去转换”

  [注意]在webpack配置中定义loader时,要定义在module.rules中,而不是rules。在定义错误时webpack会给出严重的警告

【示例】

  例如,使用loader加载CSS文件,或将TypeScript转为JavaScript。首先,安装对应的loader:

npm install --save-dev css-loader
npm install --save-dev ts-loader

  其次,配置webpack.config.js,对每个.css文件使用css-loader,然后类似地,对每个.ts文件使用ts-loader:

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

  [注意]根据配置选项,下面的规范定义了同等的loader用法:

{test: /\.css$/, loader: 'css-loader'}// 等同于{test: /\.css$/, use: 'css-loader'}// 等同于{test: /\.css$/, use: {
  loader: 'css-loader',
  options: {}
}}

【配置】

  在应用程序中,有三种使用 loader 的方式:1、通过配置;2、在 require 语句中显示使用;3、通过 CLI

通过配置

  module.rules允许在webpack配置中指定几个loader。 这是展示loader的一种简明的方式,并且有助于使代码变得简洁。而且对每个相应的loader有一个完整的概述

module: {
  rules: [
    {
      test: /\.css$/,
      use: [
        { loader: 'style-loader'},
        {
          loader: 'css-loader',
          options: {
            modules: true  }
        }
      ]
    }
  ]
}

通过require

  可以在require语句(或define,require.ensure,等语句)中指定loader。使用!将资源中的loader分开。分开的每个部分都相对于当前目录解析

require('style-loader!css-loader?modules!./styles.css');

  通过前置所有规则及使用!,可以对应覆盖到配置中的任意loader

  选项可以传递查询参数,就像在web中那样(?key=value&foo=bar)。也可以使用JSON对象(?{"key":"value","foo":"bar"})

通过CLI

webpack --module-bind jade-loader --module-bind 'css=style-loader!css-loader'

  这会对 .jade 文件使用 jade-loader,对 .css 文件使用 style-loader 和 css-loader

【特性】

  loader 支持链式传递。能够对资源使用流水线(pipeline)。loader 链式地按照先后顺序进行编译。loader 链中的第一个 loader 返回值给下一个 loader。在最后一个 loader,返回 webpack 所预期的 JavaScript

  loader 可以是同步或异步函数。loader 运行在 Node.js 中,并且能够执行任何可能的操作

  loader 接收查询参数。用于 loader 间传递配置。loader 也能够使用 options 对象进行配置

  除了使用 package.json 常见的 main 属性,还可以将普通的 npm 模块导出为 loader,做法是在 package.json 里定义一个 loader 字段

  插件(plugin)可以为 loader 带来更多特性。loader 能够产生额外的任意文件。

  loader 通过(loader)预处理函数,为 JavaScript 生态系统提供了更多有力功能。用户现在可以更加灵活的引入细粒度逻辑,例如压缩(compression)、打包(package)、语言翻译(language translation)和其他更多

【解析】

  loader 遵循标准的模块解析。多数情况下,loader 将从模块路径(通常将模块路径认为是 npm install, node_modules)解析。

  loader 模块需要导出为一个函数,并且使用 Node.js 兼容的 JavaScript 编写。在通常情况下,可以使用 npm 来管理 loader,也可以将 loader 模块作为应用程序中的文件。按照约定,loader 通常被命名为 xxx-loader(例如 json-loader)

 

插件

  插件是wepback的支柱功能。在使用webpack配置时,webpack自身也构建于同样的插件系统上。插件目的在于解决loader无法实现的其他事情。由于loader仅在每个文件的基础上执行转换,而插件(plugins)最常用于(但不限于)在打包模块的“compilation”和“chunk”生命周期执行操作和自定义功能。webpack的插件系统极其强大和可定制化。

  想要使用一个插件,只需要require()它,然后把它添加到plugins数组中。多数插件可以通过选项(option)自定义。也可以在一个配置文件中因为不同目的而多次使用同一个插件,需要使用new创建实例来调用它

【剖析】

  webpack插件是一个具有apply属性的JavaScript对象。apply属性会被webpack compiler调用,并且compiler对象可在整个compilation生命周期访问

//ConsoleLogOnBuildWebpackPlugin.jsfunction ConsoleLogOnBuildWebpackPlugin() {

};
ConsoleLogOnBuildWebpackPlugin.prototype.apply = function(compiler) {
  compiler.plugin('run', function(compiler, callback) {
    console.log("webpack 构建过程开始!!!");

    callback();
  });
};

【用法】

  由于plugin可以携带参数/选项,必须在wepback配置中,向plugins属性传入new实例

var HtmlWebpackPlugin = require('html-webpack-plugin'); //通过 npm 安装var webpack = require('webpack'); //访问内置的插件var path = require('path');var config = {
  entry: './path/to/my/entry/file.js',
  output: {
    filename: 'my-first-webpack.bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader'  }
    ]
  },
  plugins: [new webpack.optimize.UglifyJsPlugin(),new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};
module.exports = config;

 

The above is the detailed content of Detailed explanation of four basic concepts in webpack. 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