webpack基本介绍(最新版本V3.5.5)
1:webpack是一个模块打包器(module bundler)(现代JS应用程序的模块打包器)。当webpack处理应用程序时,它会递归的构建一个依赖关系图(这个关系图包含应用程序的每个模块,然后将所有这些模块打包成一个少量的bundle–通常只有一个,由浏览器加载)。
2:webpack是高度可配置的,但是在开发前,需要先了解四个核心概念:入口(entry),输出(output)。loader,插件(plugins)
入口(entry)
webpack创建应用程序所有依赖的关系图(dependency graph),图的起点被称为入口起点(entry point)。这个起点告诉webpack从哪里开始,根据依赖关系确定需要打包的内容;可以这么认为:app的第一个启动文件;在webpack中,我们使用entry属性来定义入口;如下
//webpack.config.js
module,exports={
entry:'./path/to/my/entry/file.js'
}
出口(output)
将所有的资源(assets)归拢到一起后,还需要告诉webpack在哪里打包应用程序,webpack的output属性描述了如何处理归拢到一起的代码(bundle code)
//webpck.config.js
const path=require('path');
module.exports={
entry:'./paht/to/my/entry/file.js',
output:{
path:path.resolve(_dirname,'dist'),
filename:'my-first-webpck.bundle.js'
}
}
loader
webpack的目标是,让webpack聚焦于项目中的所有资源,而浏览器不需要关注考虑这些,webpack把每个文件(.css .html .scss .jpg etc.)都作为模块处理,但是webpack自身只理解JS;因此loader便出现了,他的作用是在非JS文件被添加到依赖图中时,将其转化为模块;loader有2个目标
(1)通过test属性,识别出(identify)应该被对应的loader进行转换(transfrom)的那些文件,
(2)通过use属性,转换这些文件,从而使其能够被添加到依赖图(最终添加到bundle中)
//webpack.config.js
const path=require('path');
module.exports={
entry:'./paht/to/my/entry/file.js',
outpath:{
path:path.resolve(_dirname,'dist'),
filename:'my-first-webpck.bundle.js'
},
module:{
rules:[
{
test:/\.txt$/,
use:'raw-loader'
}
]
}
}
module.exports=fonfig;
上面代码中的module的rules告诉webpack编译器,当碰到require()/import语句中被解析为'.txt'的路径时,在你打包之前,先使用raw-loader转化一下;
插件(plugins)
webpack的插件系统及其强大和可定制化;插件更常用于(但不限于)在打包模块的’compilation’跟’chunk’生命周日执行操作和自定义功能;插件目的在于解决 loader 无法实现的其他事。
//webpack.config.js
cponst HtmlWebpackPlugin=require('html-webapck-plugin');
const webpack=require('webpack');
const path=require('path');
const config={
entry:'./path/to/my/entry/fils.js',
output:{
path:path.resolve(_dirname,'dist'),
filename:'my-first-webpack.bundle.js'
},
module:{
rules:[
{
test:/\.text/,
use:'raw-loader'
}
]
},
plugins:[
new webpack.optimize.UglifyJsPlugin(),
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
module.exports=config;