Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom loaders #2

Open
amulchinock opened this issue Jul 12, 2022 · 1 comment
Open

Custom loaders #2

amulchinock opened this issue Jul 12, 2022 · 1 comment

Comments

@amulchinock
Copy link

This library assumes that developers will have their entry files in the same directory as their source NJK files.

We have a need to support passing options to nunjucks.FileSystemLoader(), which is currently not possible.

https://mozilla.github.io/nunjucks/api.html#filesystemloader

@amulchinock
Copy link
Author

A quick suggested change would be (untested):

function NunjucksPlugin({
  input,
  output,
  vars = {},
  opts = {},
  preRenderEnvironment,
  loaders = [] // adds ability to pass in an array of loaders
} = {}) {

   if (!input) throw new Error('no input file specified');
   if (!output) throw new Error('no output file specified');
  
  const handleTemplateContent = async (templateContent, bundlePath) => {
    nunjucks.configure(opts);
    const environment = new nunjucks.Environment(loaders.length > 0 ? loaders : null); // pass the loaders to nunjucks
    if (preRenderEnvironment) preRenderEnvironment(environment);
    const rendered = environment.renderString(templateContent, {
      ...vars,
      bundlePath
    });

    const actualPathOut = actualPath(output);
    await fs.promises.writeFile(actualPathOut, rendered);
  };

  return {
    name: PLUGIN_NAME,
    async buildStart() {
      this.addWatchFile(actualPath(input));
    },
    async writeBundle(bundle) {
      const { file: bundlePath } = bundle;

      const actualPathIn = actualPath(input);
      const templateContent = await fs.promises.readFile(actualPathIn, 'utf-8');
      await handleTemplateContent(templateContent, bundlePath);
    }
  };
}

To use it:

import nunjucks from 'nunjucks';

export default {
  plugins: [
    NunjucksPlugin({
      input: 'whatever.html',
      output: 'whatever.html',
      loaders: [
        new nunjucks.FileSystemLoader('some/directory')
      ]
    })
  ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant