入口
单入口
const config = {entry: {app: './src/app.js',vendors: './src/vendors.js'}};
多入口
const config = {entry: {pageOne: './src/pageOne/index.js',pageTwo: './src/pageTwo/index.js',pageThree: './src/pageThree/index.js'}};
输出
单页
const config = {output: {filename: 'bundle.js',path: '/home/proj/public/assets'}};module.exports = config;
多页
使用占位符定义名称
{entry: {app: './src/app.js',search: './src/search.js'},output: {filename: '[name].js',path: __dirname + '/dist'}}
进阶
以下是使用 CDN 和资源 hash 的复杂示例:
config.js
output: {path: "/home/proj/cdn/assets/[hash]",publicPath: "http://cdn.example.com/assets/[hash]/"}
在编译时不知道最终输出文件的 publicPath 的情况下,publicPath 可以留空,并且在入口起点文件运行时动态设置。如果你在编译时不知道 publicPath,你可以先忽略它,并且在入口起点设置 __webpack_public_path__。
__webpack_public_path__ = myRuntimePublicPath// 剩余的应用程序入口
loader
加载模块文件和非标准js文件的编译器。
插件plugin
扩展webpack的功能。
通过实现apply原型方法,通过compiler和compilation的hooks来扩展功能。
模式
配置
- entry
- output
- mode
- module:模块解析规则的定义,各种loader的配置
- resolve:模块解析配置,如别名alias,模块目录等
- plugins:插件列表
- server:开发服务器配置
- devtool:配置sourceMap的源代码映射,方便调试代码
- targets:web/node等
- watch和watchOptions:是否监听文件变化和相关配置
- externals:防止将某些
import的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies)。 - performance:性能相关展示指标配置
- …
源码理解
tapable
要理解webpack中compiler和completion的源码需要先了解tapable相关的知识。
tapable是一个类似EventEmiter的发布订阅模式的实现。源码流程
webpack.js
webpack->create()->createCompiler(options)->new Compiler(context)->options.pluginsCompiler.js
run->compile()->newCompilation(params)->creattCompilation()->new Compilation(this)Compilation.js
