I am following a documentation and copying the same code gives me this import error inapp.js
app.js:
/*
require('dotenv').config()
const express = require('express');
const cors = require('cors');
*/
// Aquí me da el error:
import models, { connectDatabase } from './models/IndexModels'
/*
const app = express()
const port = process.env.PORT;
app.use(cors())
connectDatabase().then(async () => {
app.listen(port, () => console.log(`database up and express app running on port ${port}`))
})
*/
I have also tried to simply put: import { connectDatabase } from './models/IndexModels'
and it gives me the same error:
import { connectDatabase } from './models/IndexModels'
^
SyntaxError: Unexpected token {
This is the file I export from:
IndexModels.js:
/*
import mongoose from "mongoose"
import List from "./list"
import Task from "./task"
import User from "./user"
const connectDatabase = () => {
return mongoose.connect(process.env.DATABASE_URL);
}
*/
const models = { List, Task, User };
export { connectDatabase }
export default models;
CommonJS is the system used by
Node.js
for working with modules, your code is using native ES6 modules and these are not yet supported byNode.js
. If the code is to work directly onNode.js
try to import the modules as follows:And export them as follows:
Another solution is to use esm , install it:
And then you can run the code that works with modules
ES6
like this:Or if you have
Node 13
, you could use one of its experimental functions (working with modulesES6
). Rename the file fromjs
amjs
and run: