Node.js app with Nunjucks (Part 2)

In the first part of this tutorial, we created a basic Node.js app to use for serving pages built using Nunjucks. Now it’s time to configure Nunjucks and our app to use it.

Configuration

Firstly, install Nunjucks, and to use the file watcher built-in to Nunjucks, Chokidar, a cross-platform file-watching library, must be installed as well.

You have to also install the relevant type definition package.

Following the model-view-controller software design pattern, create a views subdirectory in the src directory. This is where your template files will be located. Then in the index.ts file set path to it.

Also remember about importing the Node.js path module (here is more about it if you are interested in details).

Next, create a Nunjucks loader, which is an object that takes a template name and loads it from a source, with a path to templates as an argument.

Also, create an object with the loader options. You really only need two: watch, which reloads templates when they are changed (server-side), and noCache, which will determine if the cache is used or templates will be recompiled every single time (see the documentation).

Of course, remember to add relevant entries to the .env file.

Finally, create a new instance of Nunjucks’s Environment class with the loader and its options.

Then install Nunjucks as the rendering engine for the Express app.

You also need to provide the view engine, which is the file extension of your template files. You can use njk, which is the one adopted by the Nunjucks community, or html, but in fact, you are free to use any file extension you wish for your Nunjucks template files since any will work.

To check if the configuration works, create a simple template in the views directory with the name index.njk.

Then create a controllers directory in the src directory, and inside it, create an indexController.ts file with a simple function that will call Nunjucks’s render function available in the response parameter. It takes the name of the template and an object with properties that will be used in the template to substitute the tags with the provided texts. You have to ensure that the property keys are the same as the tags in the template.

Next, you have to import it into index.ts

and provide as a parameter to the get request instead of the previously used arrow function.

Before you can run the app, you have to modify the scripts in package.json. First, add a new script called build that will run the preexisting clean script, which removes the build directory, then the compile script, which will run the TypeScript Compiler (tsc), and finally copy recursively the views directory.

Then modify the start script, replacing the compile script with the build script, so it’s as follows:

Now you can run your app. Happy coding!

3 thoughts on “Node.js app with Nunjucks (Part 2)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.