I am trying to use Babel 7 with Express and I have resolved all errors that have come my way, but I cannot get the Express server to start. I'm unsure if this is because there is no substitute (to my knowledge) for babel-node or if I am doing something wrong.
Here is my package.json
{
"name": "MEAN-Package",
"version": "0.1.0",
"description": "A package for the exercises",
"main": "index.js",
"author": "Chasen Bettinger",
"license": "MIT",
"scripts": {
"start": "nodemon server.js --exec babel"
},
"dependencies": {
"connect": "^3.6.6",
"express": "^4.16.3",
"mongodb": "^3.0.4"
},
"devDependencies": {
"#babel/cli": "^7.0.0-beta.42",
"#babel/core": "^7.0.0-beta.42",
"#babel/preset-env": "^7.0.0-beta.42",
"nodemon": "^1.17.2"
}
}
Here is server.js
import express from "express";
const app = express();
app.use("/", (req, res) => {
res.status(200).send("Hello World");
});
app.listen(3000);
console.log("Server running at http://localhost:3000/");
export { app as default };
My .babelrc file
{
"presets": ["#babel/preset-env"]
}
Console output:
Trying to learn express so any help is appreciated!
You should you babel-node instead of babel. Follow these steps to fix it:
Add babel-node:
yarn add #babel/node --dev
2- Change your start script on package.json to:
"scripts": {
"start": "nodemon server.js --exec babel-node",
}
You should not be using babel-node in production. It is unnecessarily heavy, with high memory usage due to the cache being stored in memory. You will also always experience a startup performance penalty as the entire app needs to be compiled on the fly.
the correct way is:
npm i -D #babel/node
and
"scripts": {
"start": "nodemon server.js --exec babel-node",
}
npm run start
Related
Let me explain further, what i mean is i have created a mern app which is already deployed on heroku now i want to make changes in the app but before i push it again on heroku i want to check my changes locally so how do i do that?
I tried the heroku local command but it starts the client side and cannot fetch the node server routes please help me out here !? here is my code:
node app.js
import express from "express";
import bodyParser from "body-parser";
import dotenv from 'dotenv'
import router from './Routes/auth.js'
import path from 'path';
dotenv.config({path:'./config.env'});
const host = '0.0.0.0';
const port = process.env.PORT || 5000;
const app= express()
app.use(router);
if(process.env.NODE_ENV === "production"){
const __dirname=path.resolve();
app.use(express.static(path.join(__dirname,"/client/build")));
app.get("*",(req,res)=>{
res.sendFile(path.resolve(__dirname,'client','build','index.html'));
})
}
app.listen(port,host,()=>{
console.log(`Server Started Succesfully on port number ${port}`);
})
package.jso(nodejs)
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npx nodemon app.js",
"client":"npm start --prefix client",
"dev":"concurrently \"npm start\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.1",
"cookie-parser": "^1.4.6",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"jsonwebtoken": "^8.5.1",
"moment": "^2.29.1",
"mongoose": "^6.1.8"
}
}
My file system
According to my testing You can do:
Check on Browser Tools: Like Responsiveness
Check your elements in DevTools
All Pages all Div tags elements, responsiveness of app, and design you can check of your app
for node server routes you can check by testing it in Postman API tool
That's it Ready to Deploy
I am trying to deploy a full-stack app on heroku, i have tried couple of things but none of them worked... when i entered "heroku logs" to follow up with the errors it should me code: 'MODULE_NOT_FOUND even though the node_module's can be found in both the Root of the project and the Frontend file as well , how do i fix this error and where does it come from ?
Here's a picture of my projects structure:
server.js:
require('dotenv').config();
const path = require('path');
const express = require("express");
const productRoutes = require("./routes/productRoutes");
const connectDB = require("./config/db");
connectDB();
const app = express();
app.use(express.json());
//--------------- deployment -------
app.use("/api/products", productRoutes);
if(process.env.NODE_ENV === "production") {
app.use(express.static(path.join('../frontend/build')));
app.get('*',(req,res) => {
res.sendFile(path.resolve(__dirname,'../frontend/build','index.html'))
})
} else {
app.get("/", (req, res) => {
res.send("Api running");
})
}
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
.env:
PORT=8080
MONGO_URI=*****
NODE_ENV=production
Package.json:
{
"name": "mern-shopping-build",
"version": "1.0.0",
"description": "Shopping list built with MERN stack",
"main": "server.js",
"engines": {
"node": "16.4.1",
"npm": "7.18.1"
},
"scripts": {
"build": "cd frontend && npm run dev",
"install-client": "cd frontend && npm install",
"heroku-postbuild": "npm run install-client && npm run build",
"start": "node server.js",
"server": "nodemon backend/server.js",
"client": "npm start && cd frontend",
"dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm start --prefix frontend\""
},
"keywords": [],
"author": "Karim ",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^5.13.2"
},
"devDependencies": {
"concurrently": "^6.2.0",
"nodemon": "^2.0.9"
}
}
ProcFile:
web node server.js
I Would appreciate any kind of feedback or help, Thank you!
A Procfile is not technically required to deploy simple apps written in most Heroku-supported languages—the platform automatically detects the language and creates a default web process type to boot the application server.
Just make sure to point your root package.json main key to backend/server.js.
Most likely it would work otherwise share your Build Logs to check it further.
{
"main": "backend/server.js"
}
I am using NextJS with typescript, mongo Atlas, mongoose, node and express.
I am getting the following error when I run node pages/server:
I have uploaded my package.json file and have added babel as well
import express from 'express'; ^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1072:16)
at Module._compile (internal/modules/cjs/loader.js:1122:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
This is my server.js code:
import express from 'express';
import { connect, connection } from 'mongoose';
import morgan from 'morgan';
import path from 'path';
const app = express();
const PORT = process.env.PORT || 8080;
//Success
import routes from './routes/api.tsx';
const MONGODB_URI = 'xxx';
// const routes=require('./routes/api')
connect(MONGODB_URI ||'mongodb://localhost/success', {
useNewUrlParser: true,
useUnifiedTopology: true
});
connection.on('connected', () => {
console.log('Mongoose is connected');
});
const newBlogPost = new BlogPost(data); //instance of the model
app.use(morgan('tiny'));
app.use('/',routes)
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
package.json file
{
"name": "la-sheild",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "next",
"build": "next build",
"start": "babel-node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#types/express": "^4.17.2",
"#types/mongoose": "^5.7.1",
"axios": "^0.19.2",
"concurrently": "^5.1.0",
"express": "^4.17.1",
"mongoose": "^5.9.1",
"morgan": "^1.9.1",
"next": "^9.2.2",
"node": "^13.8.0",
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/register": "^7.8.3",
"#types/node": "^13.7.4",
"#types/react": "^16.9.21",
"babel-cli": "^6.26.0",
"typescript": "^3.7.5"
},
"proxy": "http://localhost:8080"
}
Since Node v12, you can use either the .mjs extension or set "type": "module" in your package.json.
And you need to run node with the --experimental-modules flag.
node --experimental-modules server.mjs
You can check the SO link
Or you can create .babelrc file in the root of your project.
Add following (and any other babel presets you need, can be added in this file):
{
"presets": ["env"]
}
Install babel-preset-env using
npm install babel-preset-env
npm install babel-cli -g
# OR
yarn add babel-preset-env
yarn global add babel-cli
Now, go to the folder where your server.js file exists and
run using:
babel-node fileName.js
Or you can run using npm start by adding following code to your package.json file:
"scripts": {
"start": "babel-node server.js"
}
There is a tutorial link for Set Up Next.js with a Custom Express Server + Typescript on a medium that will be very helpful for you.
The following solution worked for me;
install needed packages
npm install nodemon #babel/core #babel/node #babel/preset-env -D
create a .babelrc file in the working directory and paste the following in it
{
"presets": [
"#babel/preset-env" ]
}
lastly, add the code below to "scripts" in package.json
"dev": "nodemon —exec babel-node server.js"
where server.js is your file in this case.
Hope this works :)
Here is the solution based on ts-next-express.
npm i --save ts-node
create another config file for express because node is using common.js module but if you check the tsconfig.json you will see this:"module": "esnext"
tsconfig.server.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "dist",
"noEmit": false
},
"include": ["server"]
}
set the script as follow:
"start": "ts-node --project tsconfig.server.json server.ts"
I was getting same error "SyntaxError: Cannot use import statement outside a module" first i add tye : module but still face another error. Finaly its work for me the issue was this i was running my Driver.js file that why i was getting this issue. i run my Driver.ts file its work ok for me.
enter image description here
But after run my with extenstion .ts file its work.
enter image description here
I had my index.ts importing an exported var from my schema.js file.
I was doing an import inside this schema.js file
It was this second import causing the 'Cannot use import statement outside modules'.
Finally renaming the file from schema.js to schema.ts solved the issue.\
"scripts": {
"start": "babel-node server.js"
}
adding above worked for me
UPDATE:
I had nvm for windows installed and forgot about it. It was projecting the contents of its node installation to the program files folder.
ORIGINAL:
So I have a very simple project copied from freecodecamp
index.js
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(3000, () => console.log('Example app listening on port 3000!'));
package.json
{
"name": "test-app", "version": "1.0.0", "description": "", "main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"keywords": [], "author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
Running node index.js starts the server and operates as expected, but if I run npm start it just returns:
> test-app#1.0.0 start D:\temp\test-app
> node index.js
Microsoft Windows [Version 10.0.17134.885]
(c) 2018 Microsoft Corporation. All rights reserved.
and exits out.
I would expect that npm start does the same thing as node index.js since it uses the same command, as described here.
What did I do wrong?
I have tried:
running npm cache clean --force
removing node_modules and running npm install
removing all traces of node and reinstalling a different version
EDIT: project structure looks like
D:\temp\test-app
├── node_modules
├── index.js
├── package-lock.json
└── package.json
Just rename your index.js file to server.js and remove the "start": script entirely. Then npm start will work normally.
{
"name": "test-app", "version": "1.0.0", "description": "", "main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [], "author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
Please try with npm run start instead of npm start in the same directory as your package.json
How do I add multiple NODE_PATH in package.json?
I want to have these multiple paths:
NODE_PATH=./ NODE_PATH=./modules/
or
NODE_PATH=./lib NODE_PATH=./modules/
package.json:
{
"name": "my-app",
"description": "env",
"repository": "https://github.com/xxx.git",
"scripts": {
"dev": "NODE_PATH=./lib NODE_PATH=./ node server.js",
"start": "cross-env NODE_ENV=production NODE_PATH=./ NODE_PATH=./modules/ nodemon --exec babel-node --presets es2015 server.js"
},
"dependencies": {
"cross-env": "^5.0.5",
"express": "^4.15.4"
},
"license": "MIT"
}
server.js:
'use strict'
import express from 'express'
import sample from 'lib/sample'
import config from 'lib'
const app = express()
const isProd = (process.env.NODE_ENV === 'production')
const port = process.env.PORT || 3000
console.log(isProd)
console.log(sample)
console.log(config)
app.get('/', function (req, res) {
const data = {message: 'Hello World!'}
console.log(data);
return res.status(200).json(data);
})
app.listen(port, function () {
console.log('listening on port 3000!')
})
Error:
Error: Cannot find module 'lib/sample'
Any ideas?
The way you are using NODE_PATH in your example, by setting it twice, you are overwriting the writing the value you assign first with the second time.
Instead, set NODE_PATH to multiple paths, delimited by colons (on MacOS or Linux) or semicolons (Windows), like this:
{
"name": "my-app",
"description": "env",
"repository": "https://github.com/xxx.git",
"scripts": {
"dev": "NODE_PATH=./lib:./ node server.js",
"start": "cross-env NODE_ENV=production NODE_PATH=./:./modules/ nodemon --exec babel-node --presets es2015 server.js"
},
"dependencies": {
"cross-env": "^5.0.5",
"express": "^4.15.4"
},
"license": "MIT"
}
See Node.js documentation:
https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders