2

I have an app that contains the following in index.js:

import express from 'express';
import data from './data/data.json';

const app = express();
const PORT = 3000;

How can I access the data variable for testing purposes?

This answer given on SO (node -i -e "$(< index.js)") returns the following error:

import express from 'express';
        ^^^^^^^

SyntaxError: Unexpected identifier

I'm on Node 10.8 and Express 4.16.3.

In Rails, you're given an interactive console (by running rails console) where you can "play around" with the environment (db et al).

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

2 Answers2

2

This is because that import statement come later so not get identified by compilers/browsers.
You can use babel as transpiler https://babeljs.io/ or try this

var express = require('express');
var data = require('./data/data.json');

const app = express();
const PORT = 3000;

Edit


Make your package.json file look like this (install packages and change script by adding babel-node)
    {.....
      "scripts": {
      ....
      "start": "babel-node Server.js"
      ...  
   },
"devDependencies": {
    "babel-cli": "^6.8.0",
    "babel-core": "6.8.0",
    "babel-loader": "6.2.4",
    "babel-preset-es2015": "6.6.0",
    "babel-preset-react": "6.5.0",
    "babel-preset-react-hmre": "1.1.1",
     .....}


create .babelrc file in root directory on project (where node_modules of project are)
{
"presets": ["react","es2015"],
"env": {
    "development": {
                                    "presets": [
                                                            "react-hmre"
                                                            ]
                                }
                }
}  

and run

npm start
Rajan Lagah
  • 2,373
  • 1
  • 24
  • 40
0
const express = require('express');
const data = require('./data/data.json');

const app = express();
const PORT = 3000;

I think this should work.

Nikhil Namal
  • 1
  • 1
  • 1