2zH / articles-collection

Chuunibyou is good!
1 stars 0 forks source link

Parcel #23

Open 2zH opened 6 years ago

2zH commented 6 years ago

Parcel

Parcel: Blazing fast, zero configuration web application bundler.

Parcel

Category:

Advanced

Source code

github.com/parcel-bundler/parcel:

Pipeline:

initialization

→ parcel plugin hook

→ HTML entry

→ source.{js,html,css,png}

→ Assets

→ Packager

→ Bundle tree

Entry

Parcel 默认入口为 HTML 文件,通过分析在 HTML 里面引入的资源进行加载。

同时:

import xxx from 'xxx'

Parcel 会实时通过 npm 进行包的补充拉取与引入。

Transform

.babelrc

.babelrc · Babel

.postcssrc

postcss/postcss

{
  "modules": true,
  "plugins": {
    "autoprefixer": {
      "grid": true
    }
  }
}

.posthtmlrc

posthtml/posthtml

{
  "plugins": {
    "posthtml-img-autosize": {
      "root": "./images"
    }
  }
}

Plugin

只要把插件安装好并保存到 package.json 中。插件需要以 parcel-plugin- 作为前缀被命名。例如 parcel-plugin-foo。任何在 package.json 中被列出的带有此前缀的依赖,都会在初始化的时候被自动加载。

Custom Asset-type

const {Asset} = require('parcel-bundler');

class MyAsset extends Asset {
  type = 'foo'; // 设置主要输出类型

  async parse(code) {
    // 将代码解析为 AST 树
    return ast;
  }

  async pretransform() {
    // 可选。在收集依赖之前转换。
  }

  collectDependencies() {
    // 分析依赖
    this.addDependency('my-dep');
  }

  async transform() {
    // 可选。在收集依赖之后转换。
  }

  async generate() {
    // 生成代码。如有需要,可返回多个转换(renditions)。
    // 结果会传到合适的 packagers 去生成最终的 bundles
    return [
      {
        type: 'foo',
        value: 'my stuff here' // 主输出
      },
      {
        type: 'js',
        value: 'some javascript', // 如若需要,此转换内容可被放到 JS 的 bundle 中
        sourceMap
      }
    ];
  }

  async postProcess(generated) {
    // 所有代码生成后的过程
    // 可用于组合多种类型资源
  }
}