Before we get started, you'll need to install Node and Yarn or npm, and create a directory for your project. Then, install Parcel using Yarn:
yarn add --dev parcel
Or when using npm run:
npm install --save-dev parcel
Now that Parcel is installed, let’s setup a
package.json file for our library. We'll use the
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 an ES 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.