How to add npm packages for client-side use in Eleventy

Suppose that you want to use my ArrayWithDefault package on the front end of an Eleventy site. What’s the easiest way to make that package available for inclusion in HTML?

First, install the package:

npm install @humanwhocodes/array-with-default

Then, in your Eleventy config file (.eleventy.js), add this inside of your default config function:

module.exports = function(eleventyConfig) {

    eleventyConfig.addPassthroughCopy({
        "./node_modules/@humanwhocodes/array-with-default/dist/array-with-default.js": "/assets/js/array-with-default.js"
    });

};

Now, array-with-default.js is placed inside the /assets/js directory, and you can modify, process, or reference that file the same way that you do any other files in that directory.

This process works for any npm package that has a defined dist directory with standalone files; for other package you may need to first generate a distributable file before copying over into the correct location.

Master JavaScript Promises

Free E-book - Understanding JavaScript Promises

What You'll Learn

  • Promise fundamentals and concepts
  • Real-world promise implementations
  • Best practices and patterns
  • Error handling techniques

Demystify JavaScript promises with practical examples and expert insights.

Download Your Free Copy

The community edition arrives in your inbox within minutes.