Détail du package

gatsby-plugin-postbuild

mohatt437MIT3.0.2

Gatsby plugin for optimizing/transforming generated static files.

gatsby, gatsby-plugin, postbuild, optimization

readme

Gatsby Postbuild

![][gatsby-img]

Provides an easy way to transform, modify or optimize static files generated by Gatsby using an extendable event-based tasks API. A Postbuild task is a set of functions that hook into certain events emitted by file transformers.

The plugin comes with these tasks out of the box:

  • Purgecss
    Optimizes HTML/CSS files by removing unused CSS selectors.
  • HTTP Headers
    Automatically generates headers configuration file for different hosting providers
  • Minify
    Minifies HTML inline scripts and styles using terser and cssnano.

Installation

Install with npm

$ npm install gatsby-plugin-postbuild

or yarn

$ yarn add gatsby-plugin-postbuild

Usage

All tasks that come bundled with the plugin are disabled by default so you will need to explicitly enable the ones you're going to use

// in your `gatsby-config.js`
plugins: [
  {
    resolve: `gatsby-plugin-postbuild`,
    options: {
      purgecss: {
        enabled: true
      },
      'http-headers': {
        enabled: true
      }
    }
  }
]

Every task has its own options that can be set as well. See tasks from more info

plugins: [
  {
    resolve: `gatsby-plugin-postbuild`,
    options: {
      purgecss: {
        enabled: true,
        ignore: ['resume/index.html'],
        allowSymbols: true
      },
      'http-headers': {
        enabled: true,
        provider: 'netlify',
        headers: {
          '[*]': {
            'X-Frame-Options': 'DENY',
            'X-XSS-Protection': '1; mode=block'
          }
        }
      }
    }
  }
]

Options

Define your own task

You can define custum events using the events option and the plugin will import them as a Postbuild task.

Lets say you want to manipulate the contents of svg files under /public, you can define a simple event like this:

options: {
  events: {
    svg: {
      contents: ({ raw, file }) => {
        // do something with the data
        return raw
      }
    }
  }
}

You can also use a glob pattern to match specific files

options: {
  events: {
    '/icons/*.svg': {
      contents: ({ raw, file }) => {
        // do something with the data
        return raw
      }
    }
  }
}

The contents event we used above is emitted by the generic file transformer which is used for unkown file types. Other known file types will have different set of events that will allow transforming files in a more structured way.

In this example, we will define an event that is specific to html files. Lets say you would like to strip out all comments from html files

options: {
  events: {
    html: {
      node: ({ node, file }) => {
        if (node.nodeName === '#comment') {
          file.adaptor.detachNode(node)
        }
      }
    }
  }
}

Learn more about the HTML file transformer

Processing options

You can change how files are processed using the processing option

options: {
  processing: {
    strategy: 'parallel',
    concurrency: 20
  }
}

Processing strategy accepts two values:

  • parallel: files will be read, processed and written in one step all at the same time (better memory consumption)
  • sequential: files will be processed in 3 steps with the last step being run in sequential order (consumes more memory but allows processing files based on data collected from all files)

Concurrency option sets the maximum number of files to process at once and can be set for both processing strategies.

You can also specifiy custom processing options for a specific file type

options: {
  extensions: {
    html: {
      strategy: 'sequential',
      concurrency: 15
    }
  }
}

Ignoring files

You can exclude specific files from being processed by the plugin using ignore option

options: {
  ignore: [
    'index.html',
    'icons/logo.svg'
  ]
}

You can also exclude files from being processed by a specific task

options: {
  purgecss: {
    ignore: [
      'index.html',
      'resume/index.html'
    ]
  }
}

Reporting

By default, the plugin:

  • generates a postbuild.log.json under /public after every build
  • prints a summary report during build with a list of file changes

You can change this behaviour using reporting option

options: {
  reporting: {
    log: true,
    console: false
  }
}

or enable/disable the reporting feature as a whole with a boolean value

options: {
  reporting: false
}

Defaults

These are the default plugin options defined in src/options.ts.

plugins: [
  {
    resolve: 'gatsby-plugin-postbuild',
    options: {
      enabled: true,
      reporting: true,
      ignore: [],
      events: {},
      processing: {
        strategy: 'parallel',
        concurrency: 10
      },
      extensions: {}
    }
  }
]

File transformers

Postbuild uses file transformers to process files of different types, file transformers read the files, processes them and emitt certain events, tasks define functions that hook into those events to perform certain actions. Thats basically how the plugin works.

Generic file transformer

Handles files with unknown extensions.

Events

contents: ({ raw, options, file, event, filesystem, gatsby }) => string

  • Emitted when the file is about to be written

HTML file transformer

Uses Parse5 to compile HTML files into AST then emits some events to be consumed by tasks.

Events

parse: ({ html, options, file, event, filesystem, gatsby }) => string

  • Emitted before parsing the HTML string

tree: ({ options, file, event, filesystem, gatsby }) => void

  • Emitted after HTML is compiled into AST

node: ({ node, options, file, event, filesystem, gatsby }) => void

  • Emitted for every AST node

serialize: ({ options, file, event, filesystem, gatsby }) => void

  • Emitted before serializing AST back to HTML string

write: ({ html, options, file, event, filesystem, gatsby }) => string

  • Emitted when the file is about to be written

Lifecycle events

These events are emitted at certain run time points.

Events

on.postbuild: ({ options, event, filesystem, gatsby }) => void

  • Emitted before processing files to allow tasks to run setup code

on.shutdown: ({ options, event, filesystem, gatsby }) => void

  • Emitted after processing files to allow tasks to run teardown code

[extension].configure: ({ config, options, event, filesystem, gatsby }) => void

  • Emitted before processing files of a certain extension to allow tasks to read/write processing options for that extension.

License

MIT

[gatsby-img]: https://img.shields.io/badge/gatsby->=3.0-blueviolet.svg?logo=gatsby

changelog

3.0.2 (2021-07-29)

Bug Fixes

  • plugin: fix license (aec6be9)
  • task:purgecss: ignore id attribute on inline styles (332f797)

3.0.1 (2021-05-09)

Bug Fixes

  • task:http-headers: fix paths with no headers (8db02b3)

3.0.0 (2021-05-09)

Bug Fixes

  • task:http-headers: add support for asset paths (98d42cb)

Documentation

  • plugin: bump minimum gatsby version to 3.0 (98aa63e)

Features

  • plugin: add assets api to allow fetching assets by their original filename (9d64f79)

BREAKING CHANGES

  • plugin: The plugin now requires at least Gatsby v3.0.4

2.3.1 (2021-05-06)

Bug Fixes

  • task:http-headers: fix / page path (9a2db7c)

2.3.0 (2021-05-06)

Features

  • task:http-headers: add support for other providers (Vercel, Firebase) (6289f61)
  • task:http-headers: change task name to http-headers (9e35fb7)

Performance Improvements

  • task:purgecss: code refactorings, no api changes (ccf5f9d)

2.2.2 (2021-04-12)

Performance Improvements

  • plugin: update cssnano to v5 (9f880c4)

2.2.1 (2021-04-09)

Bug Fixes

  • task:purgecss: shallow clone purgecss options before purging (8f6d754)

2.2.0 (2021-04-05)

Features

  • plugin: allow passing options to file transformers (fe0d323)
  • plugin: disallow processing ___gatsby node and its descendants by default (b9709a0)
  • task:minify: add new task for minifying inline html assets (bde1f9c)

Performance Improvements

  • plugin: update type declarations (6b50078)
  • task:purgecss: use Promise.map for purging styles (ad4ab7b)

2.1.1 (2021-03-18)

Performance Improvements

  • plugin: use chalk instead of plain ANSI codes (b6a8261)

2.1.0 (2021-03-17)

Features

  • plugin: add type declarations (0aa8210)

2.0.0 (2021-03-14)

BREAKING CHANGES

  • plugin: The plugin options schema has been changed

Features

  • task:netlify-headers: add header merging functionality (fbbb0d6)
  • task:netlify-headers: add link priority for sorting Link headers (bd5f82e)
  • task:netlify-headers: add option transformPathLinks for manipulating links under each path (bc144d0)
  • task:netlify-headers: add support for prerender links (c491491)
  • task:netlify-headers: support space delimited multi-value rel attribute (36131c9)
  • plugin: add events option to allow custom events to be added as a user task (f9fc71e)
  • plugin: add html.pagePath to get the path of the current html file (c6dfbb3)
  • plugin: add netlify-headers task (38dbec3)
  • plugin: add event ext.configure that allows tasks to change processing options for different extensions (edc3d10)
  • plugin: add html.write event (021e87d)
  • plugin: allow customizing concurrency and processing strategy on a per extension basis (0a364f9)
  • plugin: implemented tasks api (9facd94)
  • plugin: The plugin is now written in Typescript (83013f7)

Bug Fixes

  • plugin: add ext.configure event to plugin options schema (9d6d8cd)
  • plugin: correctly handle both 404 and 404.html (1242415)
  • plugin: fix concurrency option (04d8fc6)
  • plugin: fix glob matches sorting (6f07e36)
  • plugin: fix incorrect file size for updated files (b29e89f)
  • plugin: ignore running when there is no enabled tasks (c6514b5)
  • plugin: sort matches found by glob (a561b59)
  • task:purgecss: fix purgecss types (b97d36b)
  • task:netlify-headers: don't remove links with unsupported rel types (adc126b)
  • task:purgecss: no need to export DI container (9981160)

Performance Improvements

  • deps: no need for glob-to-regexp anymore (cda1d2d)
  • plugin: change defaultConcurrency to 10 (3c01272)
  • plugin: check for empty events options before adding user task (2602f46)
  • plugin: merge report and consoleReport options in one option reporting (cd83e3a)
  • plugin: move on.shutdown event to Postbuild.run method (d64d4e8)
  • plugin: move processFiles outside of postbuild.run (8c65b67)
  • plugin: optimized tasks api (6ded889)
  • plugin: remove file.getEventPayload and use a class property instead (2af57c4)
  • plugin: rename file events to glob (fed250f)
  • plugin: Replace option.purgecss.rejected with options.reportRejected (f8e4a91)
  • plugin: support checking for a list of extensions (a942e03)
  • plugin: use import type when possible (5410d4b)
  • plugin: use one event to handle generic files since we dont need to retain their data (daea1ba)
  • plugin: no need to include current task in event payload (3fda7ed)
  • task:purgecss: rename reportRejected to writeRejected and set it to false by default (23488f5)

1.2.2 (2021-02-20)

Bug Fixes

  • plugin: avoid mutating options.purgecss (230c4c6)

1.2.1 (2021-02-17)

Bug Fixes

  • plugin: check for assets extension before adding them (fcfd24b)
  • plugin: fix a minor bug when loading ignored files (77dd129)

Performance Improvements

  • plugin: ignore loading webpack chunks if no webpack ignores is defined (d116e4c)

Reverts

  • "chore(test): setup tests to run on both node 10 and 12" (e1faad9)

1.2.0 (2021-02-16)

Bug Fixes

  • plugin: remove unused class method (daa1ec3)
  • plugin: use _.mergeWith with a customizer to avoid merging arrays by index (ee4a3cd)

Features

  • plugin: add the ability to exclude webpack chunks, pages, css and js files from optimization (ab43853)

Performance Improvements

  • plugin: rename purgecss.allowSymbols to allowSymbols since its not being passed to purgecss (12acc1a)

1.1.3 (2021-02-15)

Bug Fixes

  • plugin: fix a TypeError when an ignored webpack chunkName doesn't exist (6014f80)
  • plugin: fixed reading external css files (8373021)
  • plugin: omit extractors option since its something we should handle it internally (f846684)

1.1.2 (2021-02-14)

Performance Improvements

  • plugin: implemented reporter.activityTimer for better console output (490c0e0)
  • plugin: improved error reporting (8fa4052)

1.1.1 (2021-02-14)

Performance Improvements

  • plugin: add debug messages for most tasks (86db102)
  • plugin: add total saving to final report (fa9eca1)
  • plugin: no need for glob anymore (72a7f72)

1.1.0 (2021-02-13)

Bug Fixes

  • plugin: lazy-load tasks module to allow utils to load first (5edeb2d)

Features

  • plugin: add support for local link and script files (da21e3e)

Performance Improvements

  • plugin: split purgecss task into several submodules for better readability and testing (fccf86a)

1.0.3 (2021-02-11)

Performance Improvements

  • plugin: change tailwind option to allowSymbols (4ec8913)
  • plugin: improved some helper functions (313ce5e)
  • plugin: remove tasks API as its not needed (07ec32a)

1.0.2 (2021-02-10)

Bug Fixes

  • plugin: uncomment this line NOW (1977dc1)

1.0.1 (2021-02-10)

Bug Fixes

  • plugin: trigger semantic-release to fix v1.0.0 (cc7c113)

1.0.0 (2021-02-10)

Features