Solving PKG Challenges: Including Asset Files and Nunjucks Views in Your Node.js App

Unlock PKG's power by adding assets and Nunjucks views to your Node.js app. Essentials in minutes.

9/21/20231 min read

In a recent Node.js project, I encountered a common challenge: packaging my application using 'PKG' while ensuring that local files, including asset files and Nunjucks views, were seamlessly included in the compiled executable. While I eventually succeeded, there were a few key insights that I'd like to share with you if you find yourself in a similar situation:

  1. Proper Package Configuration:
    If you're configuring PKG options like targets in your package.json file rather than using CLI arguments during the PKG process, remember to execute the command "pkg ." from the root directory of your Node.js application. This simple step ensures that PKG detects and respects your package.json settings. A quick check to confirm everything is working as expected is to compare the generated file's name with the app name specified in your package.json file.

  2. Handling Views and Asset Files:
    To efficiently include views and asset files, avoid using relative URLs directly in your Node.js application. Instead, utilize the path.join(__dirname, '/folder/file.format') method to create file paths. This approach maintains compatibility and ensures smooth integration.

  3. Automatic Inclusion of Files:
    To guarantee that all necessary files are included within the compiled executable, particularly when using Nunjucks views, adopt a path-based approach. Instead of rendering views like return render('index', contextData), use return render(path.join(__dirname, '/viewsFolder/index.njk'), contextData). This format enables PKG to automatically detect and include the required asset files during the packaging process.

  4. Nunjucks Configuration:
    When configuring Nunjucks, refrain from specifying a direct relative path to the views folder. Instead, leverage __dirname combined with the path.join function. For instance:
    nunjucks.configure(path.join(__dirname, 'viewsFolder'), {
    autoescape: true,
    express: app,

  5. Delve into Documentation:
    For any specialized scenarios related to your asset files, consider exploring the relevant Github Section of PKG's documentation for comprehensive guidance.

    By following these insights, you can simplify the process of including asset files and Nunjucks views in your Node.js application, making PKG packaging a smoother experience.

Thanks for reading, धन्यवाद 🙌

Follow me