1
votes

I have an app in NodeJS with Apollo Server, Graphql, etc. I want to use PM2 to have my index like a service so, when I close the console It dont stop.

When I execute npm start the server starts perfect. This is my start in package.json

"start": "nodemon ./index.js --exec babel-node -e js",

If I execute node index.js then this error appears.

/home/ubuntu/react/desafio/servidor/index.js:1
import express from 'express';
       ^^^^^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

this is my index.js code

 import express from 'express';
    import { ApolloServer, AuthenticationError } from 'apollo-server-express';
    import { typeDefs } from './data/schema';
    import { resolvers } from './data/resolvers';
    import jwt from 'jsonwebtoken';
    import dotenv from 'dotenv';
    import db from "./models";

    dotenv.config({path:'variables.env'});

    const cors = require('cors');
    const app = express();
    // enable cors

     // app.use(cors());
    const addToken = async (req) =>{

    }
    const server=  new ApolloServer({
        typeDefs,
        resolvers
    });

    server.applyMiddleware({app});
    app.listen({port:9000},()=> console.log(`Server Corriendo http://localhost:9000${server.graphqlPath}`));

what Im doing wrong?

2
What version of node are you using? 2ality.com/2019/04/… - karfau
Did you install node packages? - Devang Padhiyar

2 Answers

1
votes

node index.js will throw an error because your code is in ES6, to successfully run your code you will have to run it with babel-node which will compile it to ES5. babel-node comes with the babel-cli which you have to install.

" ./index.js --exec babel-node -e js" exactly does this which is to compile ES6 to ES5

Babel helps to turn our codes from ES6 to ES5. There are some ES6 features that our browsers and node are yet to understand, and older browsers do not understand ES6 codes, so we use babel to compile our code to ES5 so that both old browsers and new browsers can understand.

0
votes

While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.
check this node import vs require
in node 9 ** it is enabled behind a flag, and uses the .mjs extension**

node --experimental-modules my-app.mjs  

you can use require statements:

const express = require("express");  

If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel