-
Notifications
You must be signed in to change notification settings - Fork 1
Plugin Options
- Your First Plugin
PluginObjects- Plugin Options
In the previous step of this tutorial, you created a plugin that exports a Plugin object. This is fine for plugins that are only ever used by you. But if you want publish your plugin to NPM and allow other people to use it, then you probably want to allow them to customize its behavior. That means your plugin needs to accept options.
The recommended pattern for CodeEngine plugins that are published as NPM packages is to export a function that accepts options and returns a
Pluginobject.
Let's refactor our "Append Footer" plugin to accept a few options. Namely, lets allow people to customize the filter property, and the copyright year.
my-generator/plugins/footer.ts
Modify the plugin to export a function that accepts an options object. Notice that we provide default options, so the plugin will still work, even if no options are provided.
/**
* This is a CodeEngine plugin that adds a copyright footer to all HTML pages.
*/
export default function appendFooter(options = {}) {
// Use the specified year, or fallback to the current year
const year = options.year || new Date().getFullYear();
return {
name: "Append Footer",
// Use the specified filter, or fallback to our default filter
filter: options.filter || "*.html",
processFile(file) {
file.text = file.text.replace(
"</body>",
`<footer>Copyright © ${year}</footer></body>`
);
return file;
}
};
}my-generator/index.ts
We also need to make a change to the CodeEngine generator. Now that our plugin exports a function instead of an object, we need to call that function. We don't have to provide any options, since our plugin has defaults, but let's go ahead and set some options anyway.
import appendFooter from "./plugins/footer";
export default {
plugins: [
appendFooter({
year: 1999
})
]
};If you run code-engine now, you'll see that our plugin runs with the options that we specified in the generator.
my-generator/dist/index.html
Because we explicitly set the year option to 1999, the copyright footer will always use that year instead of the current year.
<html>
<body>
<h1>My Photo Library</h1>
<ul>
<li><img src="img/photo1.jpg"></li>
<li><img src="img/photo2.jpg"></li>
<li><img src="img/photo3.jpg"></li>
</ul>
<footer>Copyright © 1999</footer></body>
</html>Customization
API Reference

