Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "ReferenceError: require is not defined" error when compiling with "--experimental-modules"?

Tags:

node.js

internal.mjs:

import request from 'request-promise-native'

const rocketChatServer = 'http://localhost:3000';
const rocketChatAdminUserId = 'aobEdbYhXfu5hkeqG';
const rocketChatAdminAuthToken = '9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq';

export async function fetchUser (username) {
  const rocketChatUser = await request({
    url: `${rocketChatServer}/api/v1/users.info`,
    method: 'GET',
    qs: {
      username: username
    },
    headers: {
      'X-Auth-Token': rocketChatAdminAuthToken,
      'X-User-Id': rocketChatAdminUserId
    }
  });
  return rocketChatUser;
}

export async function loginUser (email, password) {
  const response = await request({
    url: `${rocketChatServer}/api/v1/login`,
    method: 'POST',
    json: {
      user: email,
      password: password
    }
  });
  return response;
}

export async function createUser(username, name, email, password) {
  const rocketChatUser = await request({
    url: `${rocketChatServer}/api/v1/users.create`,
    method: 'POST',
    json: {
      name,
      email,
      password,
      username,
      verified: true
    },
    headers: {
      'X-Auth-Token': rocketChatAdminAuthToken,
      'X-User-Id': rocketChatAdminUserId
    }
  });
  return rocketChatUser;
}

export async function createOrLoginUser (username, name, email, password,) {
  try {
    const user = await fetchUser(username);
    // Perfom login
    return await loginUser(email, password);
  } catch (ex) {
    if (ex.statusCode === 400) {
      // User does not exist, creating user
      const user = await createUser(username, name, email, password);
      // Perfom login
      return await loginUser(email, password);
    } else {
      throw ex;
    }
  }
}

external.mjs:

import { createOrLoginUser } from './internal.mjs';

var express = require('express');
var app = express();
app.post('/login', async (req, res) => {
// ....CODE TO LOGIN USER
    // Creating or login user into Rocket chat 
   try {
    const response = await createOrLoginUser(user.username, user.firstName, user.email, user.password);
    req.session.user = user;
    // Saving the rocket.chat auth token and userId in the database
    user.rocketchatAuthToken = response.data.authToken;
    user.rocketchatUserId = response.data.userId;
    await user.save();
    res.send({ message: 'Login Successful'});
   } catch (ex) {
     console.log('Rocket.chat login failed');
   }
})

Output:

me@test:~/node$ node --experimental-modules external.mjs
(node:7482) ExperimentalWarning: The ESM module loader is experimental.
ReferenceError: require is not defined
    at file:///home/me/node/external.mjs:3:15
    at ModuleJob.run (internal/loader/ModuleJob.js:94:14)
    at <anonymous>

All of sudden, I had to deal with node.js for some testing and I haven't experienced node.js before.

I don't think internal.mjs has any problem since it shows no error for running the command "node --experimental-modules internal.mjs". But Running it for external.mjs gives me an error and I couldn't solve it for many hours.

How can I solve this error so that it compiles?

like image 773
Miku Avatar asked Apr 29 '19 20:04

Miku


1 Answers

If you are going to use the new ESM modules, don't use require, import express:

Change:

var express = require('express');

to

import express from 'express';
like image 176
Mark Avatar answered Sep 28 '22 07:09

Mark