Giter Site home page Giter Site logo

rollup-plugin-polyfill's Introduction

rollup-plugin-polyfill

Rollup Plugin to include a polyfill in your bundle. Literally injects a require or import statement in the beginning of your entry files. This is useful if you only want to include certain logic in some variants of your build.

API

polyfill(packages)

  • packages is a list of modules to be resolved in your bundle.

Usage

Check out the example folder to see more configurations

const polyfill = require('rollup-plugin-polyfill')
const resolve = require('rollup-plugin-node-resolve')
const commonjs = require('rollup-plugin-commonjs')

const plugins = [
  resolve(),
  commonjs(),
  polyfill(['es6-object-assign/auto', './string-reverse.js']),
]

export default {
  input: 'index.js',
  output: {
    file: 'bundle.js',
    format: 'iife',
    name: 'example'
  },
  plugins: plugins
}

rollup-plugin-polyfill's People

Contributors

jrjurman avatar lukastaegert avatar perrin4869 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

rollup-plugin-polyfill's Issues

Sourcemaps

Hi, I just tried out the plugin, and rollup is giving me the following warning:

Sourcemap is likely to be incorrect: a plugin ('polyfill') was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help

Any chance you could fix this? Thanks :)
I'm using rollup 0.56.3

One last suggestion, maybe there could be a flag to configure whether to use require or import as a medium for polyfill

Seems to not work with resize-observer-polyfill

Hi,
I was trying to include resize-observer-polyfill, but it seems to not work. I think this plugin or rollup is adding $1 at the name of the polyfill.
Example: ResizeObserver turns to ResizeObserver$1

I used rollup-plugin-inject or an Import import ResizeObserver from 'resize-observer-polyfill' but I think it would be more legible if I use rollup-plugin-polyfill. ;)

Below some code of my tests:
Thanks.

Code of ResizeObserver Polyfill

/**
 * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
 * exposing only those methods and properties that are defined in the spec.
 */
var ResizeObserver = /** @class */ (function () {
    /**
     * Creates a new instance of ResizeObserver.
     *
     * @param {ResizeObserverCallback} callback - Callback that is invoked when
     *      dimensions of the observed elements change.
     */
    function ResizeObserver(callback) {
        if (!(this instanceof ResizeObserver)) {
            throw new TypeError('Cannot call a class as a function.');
        }
        if (!arguments.length) {
            throw new TypeError('1 argument required, but only 0 present.');
        }
        var controller = ResizeObserverController.getInstance();
        var observer = new ResizeObserverSPI(callback, controller, this);
        observers.set(this, observer);
    }
    return ResizeObserver;
}());

Using rollup-plugin-polyfill

Rollup config:

{
	input,
	plugins: [
		polyfill(['resize-observer-polyfill', './platform/platform.dom.js']),
		json(),
		resolve(),
		babel(),
		cleanup({
			sourcemap: true
		})
	],
	output: {
		name: 'Chart',
		file: 'dist/Chart.js',
		banner,
		format: 'umd',
		indent: false,
	},
},

Generated file after rollup - Polyfill:

var ResizeObserver$1 =
  function () {
    function ResizeObserver(callback) {
      if (!(this instanceof ResizeObserver)) {
        throw new TypeError('Cannot call a class as a function.');
      }
      if (!arguments.length) {
        throw new TypeError('1 argument required, but only 0 present.');
      }
      var controller = ResizeObserverController.getInstance();
      var observer = new ResizeObserverSPI(callback, controller, this);
      observers.set(this, observer);
    }
    return ResizeObserver;
  }();

var index = function () {
    if (typeof global$1.ResizeObserver !== 'undefined') {
      return global$1.ResizeObserver;
    }
    return ResizeObserver$1;
}();

Generated file after rollup - Usage:

var observer = new ResizeObserver(function (entries) {
  var entry = entries[0];
  resize(entry.contentRect.width, entry.contentRect.height);
});

It results at ResizeObserver is not defined because rollup generated a polyfill named ResizeObserver$1 insted of ResizeObserver

Importing directly the polyfill

Rollup config:

{
	input,
	plugins: [
		polyfill(['./platform/platform.dom.js']),
		json(),
		resolve(),
		babel(),
		cleanup({
			sourcemap: true
		})
	],
	output: {
		name: 'Chart',
		file: 'dist/Chart.js',
		banner,
		format: 'umd',
		indent: false,
	},
},

Importing ResizeObserver Polyfill directly in the code:

import ResizeObserver from 'resize-observer-polyfill';

const observer = new ResizeObserver(entries => {
	const entry = entries[0];
	resize(entry.contentRect.width, entry.contentRect.height);
});

Using rollup-plugin-inject

Rollup config:

const inject = require('@rollup/plugin-inject');
{
	input,
	plugins: [
		// set default because is the default export.
		inject({
			ResizeObserver: ['resize-observer-polyfill', 'default']
		}),
		polyfill(['./platform/platform.dom.js']),
		json(),
		resolve(),
		babel(),
		cleanup({
			sourcemap: true
		})
	],
	output: {
		name: 'Chart',
		file: 'dist/Chart.js',
		banner,
		format: 'umd',
		indent: false,
	},
},

Importing directly and rollup-plugin-inject generate the same code that works

Generated file after rollup - Polyfill:

var ResizeObserver =
  function () {
    function ResizeObserver(callback) {
      if (!(this instanceof ResizeObserver)) {
        throw new TypeError('Cannot call a class as a function.');
      }
      if (!arguments.length) {
        throw new TypeError('1 argument required, but only 0 present.');
      }
      var controller = ResizeObserverController.getInstance();
      var observer = new ResizeObserverSPI(callback, controller, this);
      observers.set(this, observer);
    }
    return ResizeObserver;
  }();

var index = function () {
    if (typeof global$1.ResizeObserver !== 'undefined') {
      return global$1.ResizeObserver;
    }
    return ResizeObserver;
}();

Generated file after rollup - Usage:

var observer = new index(function (entries) {
  var entry = entries[0];
  resize(entry.contentRect.width, entry.contentRect.height);
});

Specific example of polyfill import?

Hi!

I want to use this plugin but I am not sure how to... I want to import proxy-polyfill into my index.js but no idea how to do it. I installed the desired polyfill into node_modules and this is my rollup config.

import polyfill from 'rollup-plugin-polyfill';
import typescript from 'rollup-plugin-typescript';

export default {
  input: './src/index.ts',
  output: {
    banner: `/**
    file: './dist-bundles/iife/index.js',
    format: 'iife',
    name: 'logger'
  },
  plugins: [
    typescript({
      sourceMap: false,
      target: 'es3'
    }),
    polyfill('index.js', ['proxy-polyfill'])
  ],
};

I have tried with :
polyfill('index.js', ['proxy-polyfill'])
polyfill('index.js', ['./node_modules/proxy-polyfill'])
polyfill('./dist-bundles/iife/index.js', ['./node_modules/proxy-polyfill'])
polyfill('./dist-bundles/iife/index.js', ['proxy-polyfill'])
polyfill('./src/index.ts', ['proxy-polyfill'])

and nothing worked. I am lost... Could you guide me?

Consider changing how polyfills are injected

Currently, this plugin uses the isEntry flag in the transform hook to identify entry points. This is not really reliable, though:

  • Via this.emitFile, modules can become entry points even after they have been fully transformed. This has already been a problem for a long time. Recently, something more severe was added, though:
  • Via this.load, plugins can "pre-load" modules even before they are entry points. One technique that completely breaks this plugin is to pre-load a module in the resolveId hook before actually resolving it.

To avoid these issues, I would recommend to switch this plugin to a different technique which I also put as an example in the docs:

function injectPolyfillPlugin() {
  return {
    name: 'inject-polyfill',
    async resolveId(source, importer, options) {
      if (options.isEntry) {
        // We need to skip this plugin to avoid an infinite loop
        const resolution = await this.resolve(source, importer, { skipSelf: true, ...options });
        // If it cannot be resolved or is external, just return it so that
        // Rollup can display an error
        if (!resolution || resolution.external) return resolution;
        // In the load hook of the proxy, we want to use this.load to find out
        // if the entry has a default export. In the load hook, however, we no
        // longer have the full "resolution" object that may contain meta-data
        // from other plugins that is only added on first load. Therefore we
        // trigger loading here without waiting for it.
        this.load(resolution);
        return `${resolution.id}?entry-proxy`;
      }
      return null;
    },
    async load(id) {
      if (id.endsWith('?entry-proxy')) {
        const entryId = id.slice(0, -'?entry-proxy'.length);
        // We need to load and parse the original entry first because we need
        // to know if it has a default export
        const { hasDefaultExport } = await this.load({ id: entryId });
        let code = `import 'polyfill';export * from ${JSON.stringify(entryId)};`;
        // Namespace reexports do not reexport default, so we need special
        // handling here
        if (hasDefaultExport) {
          code += `export { default } from ${JSON.stringify(entryId)};`;
        }
        return code;
      }
      return null;
    }
  };
}

Note though that this will be a breaking change for the plugin as it raises the minimum required Rollup version to 2.66.0. Still I would very much recommend that you adopt it, especially since I see this plugin as a valuable contribution to the Rollup ecosystem (I was actually made aware of it when working on rollup/plugins#1038).

Polyfills not injected early enough

Thanks for this plugin - it is something I too wanted to implement, and add support for polyfill.io.

I've noticed that this plugin doesn't help when supporting browsers like IE11, since it doesn't appear that polyfills are injected early enough into the bundle. Is this a limitation of rollup?

Missing shims for Node.js built-ins (even after adding the modules to the polyfill plugin)

I have the following rollup.config.js file.

// rollup.config.js
const commonjs = require('@rollup/plugin-commonjs');
const resolve = require('@rollup/plugin-node-resolve');
const wasm = require('@rollup/plugin-wasm');
const polyfill = require('rollup-plugin-polyfill');

export default {
    input: 'index.js',
    output: [
        {
            file: 'dist/my-library.cjs.js',
            format: 'cjs', // CommonJS format for Node.js
        },
        {
            file: 'dist/my-library.esm.js',
            format: 'esm', // ES Module format for modern browsers
        },
        {
            file: 'dist/my-library.umd.js',
            format: 'umd', // UMD format for browsers and Node.js
            name: 'MyLibrary', // Global variable name for UMD build
            globals: {
                net: 'net',
                tls: 'tls',
                events: 'events',
                buffer: 'buffer',
                stream: 'stream',
                http: 'http',
                https: 'https',
                dns: 'dns',
                url: 'url',
                util: 'util',
                path: 'path',
                fs: 'fs'
            },
        },
    ],
    plugins: [
        resolve({ jsnext: true, preferBuiltins: true, browser: true }),
        commonjs(),
        wasm(),
        polyfill(['net', 'tls', 'events', 'buffer', 'stream', 'http', 'https', 'dns', 'url', 'util', 'path', 'fs']),
    ],
    external: ['net', 'tls', 'events', 'buffer', 'stream', 'http', 'https', 'dns', 'url', 'util', 'path', 'fs'],
};

And after building the library, I got the warning:

$ npm run build

> [email protected] build
> rollup -c --bundleConfigAsCjs


index.js โ†’ dist/my-library.cjs.js, dist/my-library.esm.js, dist/my-library.umd.js...
(!) Missing shims for Node.js built-ins
Creating a browser bundle that depends on "net", "tls", "events", "buffer", "stream", "http", "https", "dns", "url", "util", "path" and "fs". You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node

What is wrong ? I don't know this module very well and this could be a configuration error.
But I'm passing all external modules to the polyfill.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.