Home

Awesome

rollup-plugin-external-globals

test codecov install size

Transform external imports into global variables like Rollup's output.globals option. See rollup/rollup#2374

Installation

npm install -D rollup-plugin-external-globals

Usage

import externalGlobals from "rollup-plugin-external-globals";

export default {
  input: ["entry.js"],
  output: {
    dir: "dist",
    format: "es"
  },
  plugins: [
    externalGlobals({
      jquery: "$"
    })
  ]
};

The above config transforms

import jq from "jquery";

console.log(jq(".test"));

into

console.log($(".test"));

It also transforms dynamic import:

import("jquery")
  .then($ => {
    $ = $.default || $;
    console.log($(".test"));
  });

// transformed
Promise.resolve($)
  .then($ => {
    $ = $.default || $;
    console.log($(".test"));
  });

Note: when using dynamic import, you should notice that in ES module, the resolved object is aways a module namespace, but the global variable might be not.

Note: this plugin only works with import/export syntax. If you are using a module loader transformer e.g. rollup-plugin-commonjs, you have to put this plugin after the transformer plugin.

API

This module exports a single function.

createPlugin

const plugin = createPlugin(
  globals: Object | Function,
  {
    include?: ReadonlyArray<string | RegExp> | string | RegExp | null,
    exclude?: ReadonlyArray<string | RegExp> | string | RegExp | null,
    dynamicWrapper?: Function,
    constBindings?: Boolean
  } = {}
);

globals is a moduleId/variableName map. For example, to map jquery module to $:

const globals = {
  jquery: "$"
}

or provide a function that takes the moduleId and returns the variableName.

const globals = (id) => {
  if (id === "jquery") {
    return "$";
  }
}

include is a valid picomatch glob pattern, or array of patterns. If defined, only matched files would be transformed.

exclude is a valid picomatch glob pattern, or array of patterns. Matched files would not be transformed.

dynamicWrapper is used to specify dynamic imports. Below is the default.

const dynamicWrapper = (id) => {
  return `Promise.resolve(${id})`;
}

Virtual modules are always transformed.

constBindings is a boolean. If true, the plugin will use const instead of var to declare the variable. This usually happens when you try to re-export the global variable. Default is false.

Changelog