简体   繁体   English

使用“--experimental-modules”编译时如何修复“ReferenceError: require is not defined”错误?

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

internal.mjs:内部.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:外部.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.突然间,我不得不处理 node.js 进行一些测试,我之前没有体验过 node.js。

I don't think internal.mjs has any problem since it shows no error for running the command "node --experimental-modules internal.mjs".我不认为 internal.mjs 有任何问题,因为它没有显示运行命令“node --experimental-modules internal.mjs”的错误。 But Running it for external.mjs gives me an error and I couldn't solve it for many hours.但是为 external.mjs 运行它给了我一个错误,我好几个小时都无法解决它。

How can I solve this error so that it compiles?我怎样才能解决这个错误以便它编译?

If you are going to use the new ESM modules, don't use require , import express :如果你打算使用新的 ESM 模块,不要使用require , import express

Change:改变:

var express = require('express');

to

import express from 'express';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 节点 --experimental-modules - 错误:找不到模块 - Node --experimental-modules - Error: Cannot find module 如何让npm包bin运行实验模块选项? - how to let npm package bin run with experimental-modules option? 如何使用 --experimental-modules 标志永远运行 js - How to run forever js with --experimental-modules flag 如何使用节点 --experimental-modules 与 Typescript output - How to use node --experimental-modules with Typescript output 如何修复错误 Uncaught ReferenceError: require is not defined from readline function - how to fix error Uncaught ReferenceError: require is not defined from readline function 使用 --experimental-modules 后出现“ESM 模块加载器是实验性的”的 NodeJs 错误 - NodeJs error of 'The ESM module loader is experimental' after using --experimental-modules 使用--experimental-modules将ES6导入Node - ES6 imports in Node with --experimental-modules pm2 不适用于实验模块标志 - pm2 not working with experimental-modules flag 带有 --experimental-modules 标志的 VS Code 调试 - VS Code debug with --experimental-modules flag 如何修复 Uncaught ReferenceError: require is not defined - 如何修复? - How to fix Uncaught ReferenceError: require is not defined - How to fix it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM