Search code examples
javascriptrollup

Passing a variable between plugins in Rollup


How can I pass a variable between plugins in Rollup?

What I've tried:

// plugin-a.js
const pluginA = () => {
    return {
        name: 'pluginA',
        async options(options) {
            options.define = options.define || {};
            options.define['foo'] = 'bar';
        }
    }
}
// plugin-b.js
const pluginB = (options = {}) => {
    return {
        name: 'pluginB',
        buildStart: async (options) => {
            console.log(options)
        }
    }
}

I'm getting a warning:

(!) You have passed an unrecognized option
Unknown input options: define. Allowed options: acorn, acornInjectPlugins, cache, context, experimentalCacheExpiry, external, inlineDynamicImports, input, makeAbsoluteExternalsRelative, manualChunks, maxParallelFileOps, maxParallelFileReads, moduleContext, onwarn, perf, plugins, preserveEntrySignatures, preserveModules, preserveSymlinks, shimMissingExports, strictDeprecations, treeshake, watch

Solution

  • It seems passing data should be done by what Rollup refers to as Direct plugin communication. This is working for me. I feel this is very hard coupled though.

    function parentPlugin() {
      return {
        name: 'parent',
        api: {
          //...methods and properties exposed for other plugins
          doSomething(...args) {
            // do something interesting
          }
        }
        // ...plugin hooks
      };
    }
    
    function dependentPlugin() {
      let parentApi;
      return {
        name: 'dependent',
        buildStart({ plugins }) {
          const parentName = 'parent';
          const parentPlugin = plugins.find(plugin => plugin.name === parentName);
          if (!parentPlugin) {
            // or handle this silently if it is optional
            throw new Error(`This plugin depends on the "${parentName}" plugin.`);
          }
          // now you can access the API methods in subsequent hooks
          parentApi = parentPlugin.api;
        },
        transform(code, id) {
          if (thereIsAReasonToDoSomething(id)) {
            parentApi.doSomething(id);
          }
        }
      };
    }
    

    There's also Custom module meta-data, however when I read the meta I always get null.