Node - Can't Get moment.js to compile in VSCode (module and require problem)

Viewed 635

I have been using an online ide to put together my node app, but now I am trying to get it to run on my local computer. At this time, I am now running into an issue with starting it up: when I use the terminal to run "node app.js" I get the following error message:

\node_modules\moment\moment.js:7
import { hooks as moment, setHookCallback } from './lib/utils/hooks';
^^^^^^

SyntaxError: Cannot use import statement outside a module

I have found that the answer to fixing this issue is to add "type": "module" to the package.json file in the directory. However, when I add that to it and I try to run the application again, I get this error message:

app.js:2
const bodyParser = require("body-parser"),
                   ^

ReferenceError: require is not defined

Here are my imports:

const bodyParser = require("body-parser"),
methodOverride   = require("method-override"),
mongoose         = require("mongoose"),
express          = require("express"),
moment           = require("moment"),
app              = express();

So I am unsure why I cannot get both to work so my app can run; I am sure this is something simple but I am at a loss. Thank you.

3 Answers

When you add type = module you tell the compiler that you are using ES6 modules type in the application. So, now you can't use require anymore. Better way to fix the initial problem is to uninstall moment.js and try reinstalling some compatible version. As per my observation, error raised in the installed moment.js.

You should only use require in NodeJS.

The moment.js script is not meant to be used in server-side JavaScript that way. Use require('moment') instead:

const moment = require('moment');
const bodyParser = require("body-parser");

in place of - app.js:2 const bodyParser = require("body-parser")

can you try with - import bodyParser from 'body-parser'

Related