Building a library with Parcel
在开始之前，你需要先把 Node 和 Yarn（或 npm）安装好，并为你的项目创建一个目录。然后，使用 Yarn 来安装 Parcel：
yarn add --dev parcel
或者使用 npm 来安装 Parcel：
npm install --save-dev parcel
现在已经把 Parcel 安装好了，接下来为我们的项目创建一个
source 字段来指向我们的源码文件，并创建field to reference our source files, and create a
main target as the output file of our build. This will be consumed by other tools that use our library (e.g. bundlers or Node.js).
The above example uses
Now, our library exports a single function called
add, which adds its two parameters together and returns the result. Since this is written in ES module syntax using the
export keyword, Parcel will compile our code to a CommonJS module as expected by default in the
To build our library, run
dist/main.js as referenced by the
So far, we’ve been running the
parcel CLI directly, but it can be useful to create some scripts in your
package.json file to make this easier. We'll also setup a
watch script which will watch your source files for changes and rebuild automatically so you don't need to run the
build script manually in development as you make changes.
Now you can run
yarn build to build your project for release and
yarn watch in development.
CommonJS and ES modules#
Parcel accepts both CommonJS and ES modules as input, and can output one or more of these formats depending on what's declared in your
package.json. To add an ES module target, add the
module field to your
Now Parcel will output
dist/main.js as a CommonJS module, and
dist/module.js as an ES module. Tools that consume your library will choose whichever of these they support.
You can also use the file extension to indicate what type of module to output. The
.mjs extension will produce an ES module, and the
.cjs extension will produce a CommonJS module. This overrides the default behavior of the
main field. The
"type": "module" field can also be set in package.json to treat the
main field as an ES module as well. See the Node.js docs for more details.
Parcel also supports building libraries written in TypeScript. The
source field can point to your entry
types field in package.json to point to a
Now Parcel will output a
dist/types.d.ts file containing type definitions for our library in addition to the compiled code.
Now that you’ve set up your project, you're ready to learn about some more advanced features of Parcel. Check out the documentation about Targets, and see the Recipes and Languages sections for more in-depth guides using popular web frameworks and tools.