userMod2
userMod2

Reputation: 8960

Typescript - Importing a Module - Cannot Find Module

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

Answers (3)

user9966539
user9966539

Reputation:

If you are using typescript try importing like this :

import { Data} from "./Data";

let myData= new Data();

Upvotes: 0

Dat Le
Dat Le

Reputation: 326

Quick solution:

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"
  }
}

About TypeScript:

  1. TypeScript actually is a superset (not a subset) of JavaScript. typescript

  2. .ts files must be compiled into JavaScript before running on any JavaScript environment (NodeJS, browser,...).

  3. 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"
  }
}
  1. Or you can run .ts files directly with ts-node.

Upvotes: 5

Amol B Jamkar
Amol B Jamkar

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

Related Questions