question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

npm start crashed on typescript project

See original GitHub issue

I’ve created a basic TS project when trying to import article-parser project I’m getting the following error:

2022-08-13 11:14:10 error: uncaughtException: require() of ES Module /Users/myname/private/myprojectname-server/node_modules/article-parser/src/main.js from /Users/myname/private/myprojectname-server/src/services/dataExtracting.service.ts not supported.
Instead change the require of main.js in /Users/myname/private/myprojectname-server/src/services/dataExtracting.service.ts to a dynamic import() which is available in all CommonJS modules.
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/myname/private/myprojectname-server/node_modules/article-parser/src/main.js from /Users/myname/private/myprojectname-server/src/services/dataExtracting.service.ts not supported.
Instead change the require of main.js in /Users/myname/private/myprojectname-server/src/services/dataExtracting.service.ts to a dynamic import() which is available in all CommonJS modules.
    at Object.require.extensions.<computed> [as .js] (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:851:20)
    at Object.<anonymous> (/Users/myname/private/myprojectname-server/src/services/dataExtracting.service.ts:4:26)
    at Module.m._compile (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:857:29)
    at Object.require.extensions.<computed> [as .ts] (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:859:16)
    at Object.<anonymous> (/Users/myname/private/myprojectname-server/src/controllers/facts.controller.ts:4:34)
    at Module.m._compile (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:857:29)
    at Object.require.extensions.<computed> [as .ts] (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:859:16)
    at Object.<anonymous> (/Users/myname/private/myprojectname-server/src/routes/facts.route.ts:5:52)
    at Module.m._compile (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:857:29)
    at Object.require.extensions.<computed> [as .ts] (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:859:16)
    at Object.<anonymous> (/Users/myname/private/myprojectname-server/src/server.ts:9:47)
    at Module.m._compile (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:857:29)
    at Object.require.extensions.<computed> [as .ts] (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/index.js:859:16)
    at phase4 (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/bin.js:466:20)
    at bootstrap (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/bin.js:54:12)
    at main (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/bin.js:33:12)
    at Object.<anonymous> (/Users/myname/private/myprojectname-server/node_modules/ts-node/dist/bin.js:579:5)

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
israelor6commented, Aug 13, 2022

@ndaidong Sure

my package.json file:

{
  "name": "",
  "version": "0.0.1",
  "description": "",
  "author": "Israel & Neta Or",
  "license": "ISC",
  "scripts": {
    "start": "cross-env NODE_ENV=production node dist/server.js",
    "dev": "cross-env NODE_ENV=development nodemon",
    "build": "tsc && npx tsc-alias",
    "test": "jest --forceExit --detectOpenHandles",
    "lint": "eslint --ignore-path .gitignore --ext .ts src/",
    "lint:fix": "npm run lint -- --fix",
    "deploy:prod": "npm run build && pm2 start ecosystem.config.js --only prod",
    "deploy:dev": "pm2 start ecosystem.config.js --only dev",
    "killAll": "pm2 stop all"
  },
  "dependencies": {
    "@typegoose/typegoose": "^9.11.0",
    "article-parser": "7.0.0",
    "bcrypt": "^5.0.1",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.13.2",
    "compression": "^1.7.4",
    "config": "^3.3.7",
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "cross-env": "^7.0.3",
    "dotenv": "^16.0.1",
    "envalid": "^7.3.1",
    "express": "^4.18.1",
    "helmet": "^5.1.1",
    "hpp": "^0.2.3",
    "jest": "^28.1.3",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^6.5.1",
    "morgan": "^1.10.0",
    "pm2": "^5.2.0",
    "swagger-jsdoc": "^6.2.5",
    "swagger-ui-express": "^4.5.0",
    "ts-jest": "^28.0.7",
    "ts-node": "^10.9.1",
    "typescript": "^4.7.4",
    "winston": "^3.8.1",
    "winston-daily-rotate-file": "^4.7.1"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/compression": "^1.7.2",
    "@types/config": "^3.3.0",
    "@types/cookie-parser": "^1.4.3",
    "@types/cors": "^2.8.12",
    "@types/dotenv": "^8.2.0",
    "@types/express": "^4.17.13",
    "@types/helmet": "^4.0.0",
    "@types/hpp": "^0.2.2",
    "@types/jest": "^28.1.6",
    "@types/jsonwebtoken": "^8.5.8",
    "@types/mongoose": "^5.11.96",
    "@types/morgan": "^1.9.3",
    "@types/node": "^18.6.4",
    "@types/supertest": "^2.0.12",
    "@types/swagger-jsdoc": "^6.0.1",
    "@types/swagger-ui-express": "^4.1.3",
    "@types/winston": "^2.4.4",
    "@typescript-eslint/eslint-plugin": "^5.32.0",
    "@typescript-eslint/parser": "^5.32.0",
    "eslint": "^8.21.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-prettier": "^4.2.1",
    "husky": "^8.0.1",
    "lint-staged": "^13.0.3",
    "node-config": "^0.0.2",
    "node-gyp": "^9.1.0",
    "nodemon": "^2.0.19",
    "prettier": "^2.7.1",
    "supertest": "^6.2.4",
    "tsconfig-paths": "^4.1.0"
  }
}

My tsConfig.ts file:

{
  "compileOnSave": false,
  "compilerOptions": {
    "target": "es2020",
    "lib": ["es2020", "esnext.asynciterable"],
    "typeRoots": ["node_modules/@types"],
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "module": "commonjs",
    "pretty": true,
    "sourceMap": true,
    "declaration": true,
    "outDir": "./dist",
    "allowJs": true,
    "noEmit": false,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "importHelpers": true,
    "baseUrl": "src",
    "paths": {
      "@/*": ["*"],
      "@controllers/*": ["controllers/*"],
      "@databases": ["databases"],
      "@dtos/*": ["dtos/*"],
      "@exceptions/*": ["exceptions/*"],
      "@interfaces/*": ["interfaces/*"],
      "@middlewares/*": ["middlewares/*"],
      "@models/*": ["models/*"],
      "@routes/*": ["routes/*"],
      "@services/*": ["services/*"],
      "@utils/*": ["utils/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.json", ".env"],
  "exclude": ["node_modules", "src/tests/*.test.ts"]
}

My service:

const { extract } = require('article-parser/dist/cjs/article-parser.js');

export const getArticle = async (url: string) => {
  return await extract(url);
};

My app.ts file

process.env['NODE_CONFIG_DIR'] = __dirname + '/configs';

import compression from 'compression';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import config from 'config';
import express from 'express';
import helmet from 'helmet';
import hpp from 'hpp';
import morgan from 'morgan';
import { connect, set } from 'mongoose';
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import { dbConnection } from '@databases';
import { Routes } from '@interfaces/routes.interface';
import errorMiddleware from '@middlewares/error.middleware';
import { logger, stream } from '@utils/logger';

class App {
  public app: express.Application;
  public port: string | number;
  public env: string;

  constructor(routes: Routes[]) {
    this.app = express();
    this.port = process.env.PORT || 3000;
    this.env = process.env.NODE_ENV || 'development';

    this.connectToDatabase();
    this.initializeMiddlewares();
    this.initializeRoutes(routes);
    this.initializeSwagger();
    this.initializeErrorHandling();
  }

  public listen() {
    this.app.listen(this.port, () => {
      logger.info(`=================================`);
      logger.info(`======= ENV: ${this.env} =======`);
      logger.info(`🚀 App listening on the port ${this.port}`);
      logger.info(`=================================`);
    });
  }

  public getServer() {
    return this.app;
  }

  private connectToDatabase() {
    if (this.env !== 'production') {
      set('debug', true);
    }

    connect(dbConnection.url).then(() => logger.info('🚀 Connected to the database'));
  }

  private initializeMiddlewares() {
    this.app.use(morgan(config.get('log.format'), { stream }));
    this.app.use(cors({ origin: config.get('cors.origin'), credentials: config.get('cors.credentials') }));
    this.app.use(hpp());
    this.app.use(helmet());
    this.app.use(compression());
    this.app.use(express.json());
    this.app.use(express.urlencoded({ extended: true }));
    this.app.use(cookieParser());
  }

  private initializeRoutes(routes: Routes[]) {
    routes?.map(route => {
      this.app.use('/', route.router);
    });
  }

  private initializeSwagger() {
    const options = {
      swaggerDefinition: {
        info: {
          title: 'REST API',
          version: '1.0.0',
          description: 'Example docs',
        },
      },
      apis: ['swagger.yaml'],
    };

    const specs = swaggerJSDoc(options);
    this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
  }

  private initializeErrorHandling() {
    this.app.use(errorMiddleware);
  }
}

export default App;
1reaction
ndaidongcommented, Aug 13, 2022

@israelor6 it seems you are using require to import. Could you try commonjs syntax?

const { extract } = require('article-parser/dist/cjs/article-parser.js')
Read more comments on GitHub >

github_iconTop Results From Across the Web

npm run watch crashes after any change in vue or js files ...
Both npm run dev and prod works properly, however when I try to run watch, and change files, npm run watch throws an...
Read more >
Brower crashes when running Typescript application #19510
Brower crashes when running Typescript application #19510 ... The app will run as expected when running the npm run dev task.
Read more >
Typescript Basic Node.js Express app crashes at launch
It's working now. In the project's solution explorer is a node named "nmp", open the node. In this node are 3 packages, namely...
Read more >
Let It Crash: Best Practices for Handling Node.js Errors on ...
It's simpler to let it crash, start a new process from scratch, and continue receiving more requests. We're explicitly “crashing” the Node. js ......
Read more >
ts-node-dev - npm
Start using ts-node-dev in your project by running `npm i ... files changes (as standard node-dev ) but shares Typescript compilation ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found