1
votes

Below is my project location on the GitHub:

https://github.com/nandy2013/MERN-Stack-Dev

I am just trying to import the method from the js file on another js file with below implementation:

is-empty.js

const isEmpty = value =>
value === undefined ||
value === NULL ||
(typeof value === 'object' && Object.keys(vale).length === 0) ||
(typeof value === 'string' && value.trim().length === 0);

module.exports = isEmpty;

register.js

//code
import isEmpty from './is-empty';
//code

Snippet:

enter image description here I am getting below error message

C:\Users\1217688\Desktop\devconnector\validation\register.js:2 import isEmpty from './is-empty'; ^^^^^^

SyntaxError: Unexpected token import at new Script (vm.js:51:7) at createScript (vm.js:138:10) at Object.runInThisContext (vm.js:199:10) at Module._compile (module.js:624:28) at Object.Module._extensions..js (module.js:671:10) at Module.load (module.js:573:32) at tryModuleLoad (module.js:513:12) at Function.Module._load (module.js:505:3)

Any help please!

2

2 Answers

2
votes

By default, node.js does not support ECMAScript's import statements, so instead of writing import isEmpty from './is-empty'; you should write const isEmpty = require('./is-empty');.

If you prefer to use import statements, you can enable ECMAScript Modules support by adding --experimental-modules argument to Node. But please be aware that their support is still experimental and it is not recommended to use them in production environments. In your case, you'll need to edit the package.json file of your project and replace start script command to:

node --experimental-modules ./server.js
0
votes

The latest versions of node.js supports ES6. So you can export your function directly and import it.

const isEmpty = value => {
  value === undefined ||
    value === NULL ||
    (typeof value === 'object' && Object.keys(vale).length === 0) ||
    (typeof value === 'string' && value.trim().length === 0);
}

export default isEmpty; 

And in your other file you can import as "import isEmpty from './isEmpty'". If you are exporting just one function, use default export.