0

The code for pug.compiler.js is:


/**
 * Pug Utilities
 */
 const {compileFile} =require('pug');
 /**
  * 
  * @param {String} relativeTemplatePath Pug template name
  * @param {Object} [data] Object
  * @returns {String} HTML
  */
 export function compile(relativeTemplatePath, data){
     let absoluteTemplatePath = process.cwd() + '/src/views/' + relativeTemplatePath + '.pug';
     let compiledTemplate = compileFile(absoluteTemplatePath)(data);
     return compiledTemplate;
 };

The error is :

 export function compile(relativeTemplatePath, data){
 ^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:984:16)
    at Module._compile (internal/modules/cjs/loader.js:1032:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Module.require (internal/modules/cjs/loader.js:957:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (D:\ProgramData\projects\nodejs\whatsapp\test\app.js:11:22)
    at Module._compile (internal/modules/cjs/loader.js:1068:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)

So I have a problem understanding how do I use this export function. I think it should work right?

grootste
  • 1
  • 1

1 Answers1

0

The problem is NodeJS considers module by default as CommonJS Modules.

So instead of export you should use module.exports, or if you're using NodeJS v13+ you can enable ES Modules by either:

  • Changing the extension of your file to mjs
  • Adding "type": "module" property to your package.json

Using module.exports should be like:

function compile(relativeTemplatePath, data){
     let absoluteTemplatePath = process.cwd() + '/src/views/' + relativeTemplatePath + '.pug';
     let compiledTemplate = compileFile(absoluteTemplatePath)(data);
     return compiledTemplate;
 };

module.exports = {compile};
Ron B.
  • 1,502
  • 2
  • 7
  • ``` module.exports function compile(relativeTemplatePath, data) ``` This should work right but it shows an error at function. Why? – grootste May 19 '21 at 09:08
  • Ok, my bad, I didn't mean to literally replace the word `export` with `module.exports`, I mean to you the feature. It should be `module.exports = {compile}` AFTER you defined the function, at the end of your file – Ron B. May 19 '21 at 09:13