您的位置:首页 > Web前端 > Webpack

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

2017-09-25 17:06 459 查看
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属性来定义入口。

[b]实例[/b]

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


出口(Output)

将所有的资源(assets)归拢在一起后,还需要告诉webpack 在哪里 打包应用程序。

output属性描述了如何处理归拢在一起的代码(bundle code)

[b]实例[/b]

// webpack.config.js
const 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有两个目标:

识别出(identify)应该被对应的loader进行转换(transform)的那些文件。(test属性)

转换这些文件,从而使其能够被添加到依赖图中(并且最终添加到bundle中)。(use属性)

[b]实例[/b]

// webpack.config.js
const 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 来创建它的一个实例。

[b]实例[/b]

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
const 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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  webpack