DEV Community

Jay
Jay

Posted on • Edited on

6 2

How to create your first rollup plugin

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application

Getting Started

  • Create copyFile function
    • name is the name of your plugin
    • targets array of src and dest
    • hook it is buildEnd (execute after bundling) or buildStart (execute before bundling)
const copyFile = (options = {}) => {
  const { targets = [], hook = 'buildEnd' } = options
  return {
    name: 'copy-file',
    [hook]: async() => {

    }
  }
} 
  • Copy file implementations
    • Lets add dependencies and add some codes
    • Since targets is array let's loop thru each target
    • when target.dest is not exist create the directory
    • then copy and override the file if exist
    • now we can exports our copyFile plugin
  const { basename, join } = require('path')
  const fs = require('fs/promises')

    ...
    [hook]: () => {
      targets.forEach(async target => {
        await fs.mkdir(target.dest, { recursive: true })

        const destPath = join(target.dest, basename(target.src))
        await fs.copyFile(target.src, destPath)
      })
    }
    ...

   module.exports = copyFile
  • Create rollup.config.js and use our copyFile plugin
const copyFile = require('./plugin')

export default {
  input: './src/index.js',
  plugins: [
    copyFile({
      targets: [
        { src: './index.html', dest: 'dist' }
      ]
    })
  ],
  output: {
    file: './dist/index.js',
    format: 'es'
  }
}

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay