I’m writing a plugin in the form of a default export like the code below. I want to be able to pass an object as default plugin options, this way:
// Normal call without options
Alpine.plugin(MyPlugin);
// Call with options
Alpine.plugin(MyPlugin.defaults({ foo: "bar" }));
I can easly solve adding let defaultOptions
outside the scope of the plugin itself (that is, in the root of the module):
// src/myplugin.ts
let defaultOptions: MyPluginOptions;
const MyPlugin = (Alpine: Alpine) => {
// Use defaultOptions here
};
// Expose a way to set default options
MyPlugin.defaults = (options: MyPluginOptions) => {
defaultOptions = options;
return MyPlugin;
};
export default MyPlugin;
Do I have any other option to move it inside the plugin itself?
2
Answers
Calling
MyPlugin.defaults
, if used like this, should not globally set thedefaultOptions
for all usages of the plugin. Instead, it should create a new plugin that is configured with those defaults. You can use the factory pattern for this:This even lets you chain the plugin creation:
you can move the
defaultOptions
variable inside the plugin itself by using a closure to encapsulate the variable within the scope of theMyPlugin
function.