Resource Type
Resource Types
As described in the Resource Documentation, Parcel describes each input file as an Asset. Asset types are described as classes that inherit from the Asset base class and implement the required interfaces for parsing, analyzing dependencies, transformations, and code generation.
Because Parcel processes resources in parallel across multiple processor cores, resource types can perform transformations that are limited to transformations that operate on a single file at a time. To convert across multiple files, you can use a custom Packager.
Resource interface
const {Asset} = require('parcel-bundler'); class MyAsset extends Asset { type = 'foo'; // 设置主输出类型 parse(code) { // 将代码解析为 AST return ast; } pretransform() { // 可选。在收集依赖之前转换。 } collectDependencies() { // 分析依赖 this.addDependency('my-dep'); } transform() { // 可选。在收集依赖之后转换。 } generate() { // 生成代码。如有需要,可提供多个返回。 // 结果会传到合适的 packagers 去生成最终的文件束 return { foo: 'my stuff here', // 主输出 js: 'some javascript' // 如若需要,此转换内容可被放到 JS 文件束中 }; } }
Register resource type
You can use the addAssetType method to register your resource type through the packager. It accepts the file extension to be registered and the path to the resource type module. This is a path, not an actual object, done so that it can be passed to the worker process.
const Bundler = require('parcel-bundler'); let bundler = new Bundler('input.js'); bundler.addAssetType('.ext', require.resolve('./MyAsset'));