How to use npm packages in your 11ty project

Posted on: 14-2-2024

This post will explain how to add npm packages to your 11ty project by installing a typewriter-effect package and using it in our template. It will consist of three steps.

  1. Npm install your wanted package
  2. Extend your eleventy config
  3. Use the package in your template

1. Npm install your wanted package

Install your package using npm install. We will be using the following command:

npm i typewriter-effect

This will add the dependency to your node_modules folder.

2. Extend your eleventy config

We have to tell eleventy to copy the code of our package to our output folder during build time. We can do that by leveraging .addPassthroughCopy.

Because we want to change the output location of our copied file we pass an object to the function with the format {"input": "target"}.

module.exports = function (eleventyConfig) {
  eleventyConfig.addPassthroughCopy({'./node_modules/typewriter-effect/dist/core.js': '/js/typewriter-effect.js'});

  return {
    dir: {
      input: "src",
      output: "dist"
    }
  }
};

This will put the input file in the location /js/typewriter-effect.js. Which can be used for later reference.

3. Use the package

We will use the typewriter-effect package in one of our templates. Go to your template and include the js file you just told eleventy to copy to the output directory during build time.

Like so:

<script src='/js/typewriter-effect.js'></script>
<script type="text/javascript">
    const instance = new Typewriter('#typewriter');

    instance
      .typeString("Hello world")
      .start();
</script>

You can use the same steps for other packages.