Reputation: 8960
I have this schema in file data.ts
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const DataSchema = new Schema(
{
id: Number,
message: String,
},
{ timestamps: true }
);
module.exports = mongoose.model('Data', DataSchema);
When I try to import this in my index.js as :
const Data = require('./data');
I keep seeing this error:
internal/modules/cjs/loader.js:584
throw err;
^
Error: Cannot find module './data'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
at Function.Module._load (internal/modules/cjs/loader.js:508:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
Any ideas why this is.
I've tried doing:
export const data = mongoose.model('Data', DataSchema);
then importing with import { data as Data } from './data'
But that also returns the following error:
import { data as Data } from './data'
^
SyntaxError: Unexpected token {
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
Upvotes: 9
Views: 26712
Reputation:
If you are using typescript try importing like this :
import { Data} from "./Data";
let myData= new Data();
Upvotes: 0
Reputation: 326
Use ts-node
to run your TypeScript files directly
npm install --dev ts-node
Start a node process with this command:
node -r ts-node/register index.ts
Make sure your package.json
should contain something like these:
{
"dependencies": {
"mongoose": "^5.6.10",
"typescript": "^3.5.3"
},
"devDependencies": {
"ts-node": "^8.3.0"
}
}
TypeScript
actually is a superset (not a subset) of JavaScript.
.ts
files must be compiled into JavaScript before running on any JavaScript environment (NodeJS, browser,...).
Normally in a TypeScript project, we will have a build
command in package.json
, which will compile your .ts
files into .js
files, follow with a start
command to start a node process with compiled js
file:
{
"scripts": {
"build": "tsc index.ts",
"start": "node index.js",
"start:dev": "node -r ts-node/register index.ts"
}
}
.ts
files directly with ts-node.Upvotes: 5
Reputation: 1257
You need to export your model like this,
const Data = mongoose.model('Data', DataSchema);
export default Data;
And can import it in any file like,
import Data from "./Data";
Upvotes: -3