I am just trying to get the import/export code to work within a browser using babel-node. But so far i have only been able to get it to work with one file. I keep getting Uncaught SyntaxError: Unexpected token { in the console which no doubt means it is not being converted with babel.
I have tried using different flags within the package.json file for running the app. As well as moving files to different folders and directories.
// App.js
const express = require('express');
const path = require('path');
const app = express();
console.log('App file')
app.get('/', (req, res) => res.sendFile(path.join(__dirname+'/index.html')));
app.use('/static', express.static('src'))
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Server running on port ${port}.`))
package.json
{
"name": "babel-test",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "nodemon app.js src/** --exec babel-node",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "AB",
"license": "MIT",
"dependencies": {
"axios": "^0.18.0",
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"express": "^4.16.4",
"nodemon": "^1.18.9"
}
}
Folder Tree
├── app.js
├── index.html
├── node_modules
├── package-lock.json
├── package.json
├── public
└── src
├── index.js
├── script1.js
├── script2.js
├── script3.js
└── script4.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>NodeJS</title>
</head>
<body>
<h1>Hi there from Nodejs</h1>
<script src="http://localhost:8000/static/script1.js"></script>
<script src="http://localhost:8000/static/script2.js"></script>
</body>
</html>
All it needs to do is work with import and export statements between files without errors.