MaxCore
MaxCore

Reputation: 2728

Rollup: make module globally accessible without need to import

I want module sync-fetch to be accessible globally without need to import in each component and be named as simple fetch.

Also I want to extend it with custom method then.

Now in rollup.config.js there are:

export default {
    ...
    output: {
        ...
        intro: `const fetch = require('sync-fetch');
                fetch.Response.prototype.then = function(foo) {
                    return foo(this);
                }`
    },

};

And it works, but looks dangerous) Is intro is the only way to do it?

Upvotes: 0

Views: 97

Answers (1)

Faris Ansari
Faris Ansari

Reputation: 285

If you want to make it seem less dangerous, you could put that code in a file and then return the contents of it in a function. The output.intro option also takes a function that returns the code as a string.

{
  output: {
    intro: () => require('fs/promises').readFile('path/to/the/file.js', 'utf-8')    
  }
}

Upvotes: 1

Related Questions