Webpack之核心概念学习笔记(1)

来源:互联网 发布:手机人体建模软件 编辑:程序博客网 时间:2024/06/15 21:38
  • webpack是一个现代JavaScript应用程序的模块打包器(module bundle)。
  • 当webpack处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成少量的bundle-通常只有一个,由浏览器加载。
  • 高度可配置
  • 四个核心:入口(entry)、输出(output)、loader、插件(plugins)

入口(Entry)

依赖关系图的起点被称之为入口起点(entry point)。入口起点告诉webpack从哪里开始,并根据依赖关系图确定需要打包的内容。可以将应用程序的入口起点认为是根上下文(contextual root) 或app第一个启动文件
在webpack中,使用webpack配置对象(webpack configuration object) 中的entry属性来定义入口。

实例
// webpack.config.jsmodule.exports = {    entry: './path/to/my/entry/file.js'};

出口(Output)

将所有的资源(assets)归拢在一起后,还需要告诉webpack 在哪里 打包应用程序。
output属性描述了如何处理归拢在一起的代码(bundle code)

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

Loader

webpack把每个文件(.css, .html, .scss, .jpg, etc.)都作为模块处理,而webpack自身只理解JavaScript。
webpack Loader 在文件被添加到依赖图中时,其转换为模块

在更高层面,在webpack配置中loader有两个目标:

  1. 识别出(identify)应该被对应的loader进行转换(transform)的那些文件。(test属性)
  2. 转换这些文件,从而使其能够被添加到依赖图中(并且最终添加到bundle中)。(use属性)
实例
// webpack.config.jsconst path = require('path');config = {    entry: './path/to/my/entry/file.js',    output: {        path:path.resolve(_dirname, 'dist'),        filename: 'my-first-webpack.bundle.js'    },    module: {        rules: [            { test: /\.txt$/, use: 'raw-loader' }        ]    }};module.exports = config;

test和use告诉webpack编译器如下信息:
当碰到[在require()/import语句中被解析为’.txt’的路径]时,对它打包前,先使用raw-loader转换一下

插件(Plugins)

常用于(但不限于)在打包模块的”compilation”和”chunk”生命周期执行操作和自定义功能。

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

实例
// webpack.config.jsconst HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npmconst webpack = require('webpack'); //to access built-in pluginsconst path = require('path');config = {    entry: './path/to/my/entry/file.js',    output: {        path:path.resolve(_dirname, 'dist'),        filename: 'my-first-webpack.bundle.js'    },    module: {        rules: [            { test: /\.txt$/, use: 'raw-loader' }        ]    },    plugins: [        new webpack.optimize.UglifyJsPlugin(),        new HtmlWebpackPlugin({template: './src/index.html'})    ]};module.exports = config;
原创粉丝点击