入口

单入口

  1. const config = {
  2. entry: {
  3. app: './src/app.js',
  4. vendors: './src/vendors.js'
  5. }
  6. };

多入口

  1. const config = {
  2. entry: {
  3. pageOne: './src/pageOne/index.js',
  4. pageTwo: './src/pageTwo/index.js',
  5. pageThree: './src/pageThree/index.js'
  6. }
  7. };

输出

单页

  1. const config = {
  2. output: {
  3. filename: 'bundle.js',
  4. path: '/home/proj/public/assets'
  5. }
  6. };
  7. module.exports = config;

多页

使用占位符定义名称

  1. {
  2. entry: {
  3. app: './src/app.js',
  4. search: './src/search.js'
  5. },
  6. output: {
  7. filename: '[name].js',
  8. path: __dirname + '/dist'
  9. }
  10. }

进阶

以下是使用 CDN 和资源 hash 的复杂示例:
config.js

  1. output: {
  2. path: "/home/proj/cdn/assets/[hash]",
  3. publicPath: "http://cdn.example.com/assets/[hash]/"
  4. }

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

  1. __webpack_public_path__ = myRuntimePublicPath
  2. // 剩余的应用程序入口

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.plugins

    Compiler.js

    run->compile()->newCompilation(params)->creattCompilation()->new Compilation(this)

    Compilation.js

Stats