DEV Community

loading...

How to create your first rollup plugin

Jay
I never wanted to be famous, I wanted to be great
Updated on ・1 min read

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'
  }
}

Discussion (0)