-
Notifications
You must be signed in to change notification settings - Fork 1
Advanced Plugins
- Adding and Deleting Files
- Multi-Threaded Plugins
- Accessing All Files
- Automatic Rebuilds
- Other Plugin APIs
In the previous tutorial you learned how to modify a file. But how do you remove a file? Or create a new one? Or split one file into multiple files? The answer to all of these is the same: just return what you want.
CodeEngine plugins are pure functions. That is, they accept input and return output. The output may be the same file that was received as input, but it doesn't have to be. You can return a new file, multiple files, or nothing at all.
Let's start by demonstrating how to create a new file. For example, you may create a plugin that minifies CSS files, and you want your plugin to return both the original CSS file and the new minified file. Here's how that might look:
/**
* This is a CodeEngine plugin that minifies CSS files.
* It returns the original (un-minified) file as well as the new (minified) file.
*/
export default function minifyCSS() {
return {
name: "Minify CSS",
filter: "**/*.css",
processFile(file) {
// The minified file will have the same path,
// but with a ".min.css" extension
let path = file.path.replace(/\.css$/, ".min.css");
// Minify the CSS using some third-party minifier library
let text = minify(file.text);
// Create a new file
let minifiedFile = { path, text };
// Return the original file and the minified file
return [file, minifiedFile];
}
};
}Notice that instead of just returning the original file, we returned an array containing the original file and a new file. The new file is a FileInfo object.
Perhaps your plugin needs to delete a file. That is, the file shouldn't be sent to any of the following plugins, and it shouldn't be written to the destination. In that case, simply don't return the file from your plugin.
Here's an example of a plugin that blocks drafts in production mode, but allows them in local development mode:
/**
* This is a CodeEngine plugin that prevents drafts from being published
* when in production mode, but allows them in dev mode.
*/
export default function drafts(file, run) {
if (run.dev || !file.metadata.draft) {
return file;
}
}This plugin checks for a draft flag on the File.metadata object to determine if a file is a draft. It also checks the dev flag of the Run object to determine whether CodeEngine is running in development mode or production mode. If the dev flag is true, or the draft flag is false, then the file is returned, which means it will continue being processed by other plugins and eventually written to the destination. Otherwise, the plugin doesn't return the file, which stops it from being processed or written.
Customization
API Reference

