简体   繁体   English

Node + create-react-app + Express - 如何将函数导入 Express

[英]Node + create-react-app + Express - how to import function into Express

I am using socket.IO running in Express to distribute data among clients.我正在使用在 Express 中运行的 socket.IO 在客户端之间分发数据。 To gain that data I need to use a function from another file.为了获得这些数据,我需要使用另一个文件中的函数。 Now if I understand it correctly Node + Express doesn't natively support import / export key words, which I am using in the client (React) side of the app.现在,如果我理解正确,Node + Express 本身并不支持导入/导出关键字,我在应用程序的客户端 (React) 端使用了这些关键字。 Because of that I have used "require" inside the server file:因此,我在服务器文件中使用了“require”:

server.js服务器.js

const initialStateFunctions  = require("../components/functions/InitialStateFunctions");
const playerStates = initialStateFunctions.getInitialPlayerStates();

InitialStateFunctions.js InitialStateFunctions.js

import {shuffleArray} from "./CardManipulationFuntions";
import {ARTIFACTS, CARD_STATE, CARD_TYPE, GUARDIANS, ITEMS} from "../../data/cards";
import {GLOBAL_VARS} from "../../App";
import {LOCATION_LEVEL, LOCATION_STATE, LOCATIONS} from "../../data/locations";

/* INITIAL PLAYER STATE */
export function getInitialPlayerStates() {

However now Express doesn't load because of this error:但是,由于此错误,现在 Express 无法加载:

> lore_hunters@0.1.0 start C:\Projects\lore_hunters
> node src/server/server.js

C:\Projects\lore_hunters\src\components\functions\InitialStateFunctions.js:1
import {shuffleArray} from "./CardManipulationFuntions";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1063:16)
    at Module._compile (internal/modules/cjs/loader.js:1111:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
    at Module.load (internal/modules/cjs/loader.js:996:32)
    at Function.Module._load (internal/modules/cjs/loader.js:896:14)
    at Module.require (internal/modules/cjs/loader.js:1036:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (C:\Projects\lore_hunters\src\server\server.js:11:32)
    at Module._compile (internal/modules/cjs/loader.js:1147:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! lore_hunters@0.1.0 start: `node src/server/server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the lore_hunters@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I would like to retain using import / export modules in InitialStatesFunction - how then should I import the getInitialPlayerState function into the server.js application?我想在 InitialStatesFunction 中保留使用导入/导出模块 - 那么我应该如何将 getInitialPlayerState 函数导入 server.js 应用程序? Do I need to somehow turn server.js to a module?我需要以某种方式将 server.js 转换为模块吗? (" Cannot use import statement outside a module") (“不能在模块外使用导入语句”)

EDIT: I understand that Node doesn't natively use import and the require is to be used.编辑:我知道 Node 本身并不使用import并且require使用require The problem is that the loaded module than returned the error I have listed in my question.问题是加载的模块返回了我在问题中列出的错误。

EDIT2: When using "type": "module" option for the newer version of Node, I can rewrite the server.js file to use imports instead of requires: EDIT2:当对较新版本的 Node 使用 "type": "module" 选项时,我可以重写 server.js 文件以使用导入而不是需要:

import express from "express";
import http from "http"
import socketIO from "socket.io"
import path from "path"
import {getInitialPlayerStates} from "../components/functions/InitialStateFunctions";

const port = process.env.PORT || 4001;
const app = express();
// server instance
const server = http.createServer(app);

const playerStates = getInitialPlayerStates();

However this thows following error:但是,这会出现以下错误:

(node:12816) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.js:61
  let url = moduleWrapResolve(specifier, parentURL);
            ^

Error: Cannot find module C:\Projects\lore_hunters\src\components\functions\InitialStateFunctions imported from C:\Projects\lore_hunters\src\server\server.js
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
    at Loader.resolve (internal/modules/esm/loader.js:85:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:191:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
    at link (internal/modules/esm/module_job.js:41:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

The path shown in the output seemes to be correct.输出中显示的路径似乎是正确的。 The folder structure follows:文件夹结构如下:

项目文件结构

EDIT: it seems that imports have to have file extension specified ( https://medium.com/@nodejs/announcing-core-node-js-support-for-ecmascript-modules-c5d6dc29b663 ) - that was easy to fix, however then the server has problem with JSX:编辑:似乎导入必须指定文件扩展名( https://medium.com/@nodejs/annoucing-core-node-js-support-for-ecmascript-modules-c5d6dc29b663 ) - 但是很容易修复那么服务器有 JSX 问题:

        effectsText: <Coin/>,
                     ^
SyntaxError: Unexpected token '<'

Add "type": "module" to package.json in server project if you need to use es6 modules in node.如果需要在 node 中使用 es6 模块,请在服务器项目的 package.json 中添加 "type": "module"。 with this, all .js and .mjs files are interpreted as ES modules.这样,所有 .js 和 .mjs 文件都被解释为 ES 模块。 You can interpret individual files as CommonJS by using the .cjs extension.您可以使用 .cjs 扩展名将单个文件解释为 CommonJS。

EDIT: beware that it is not possible to mix imports with require - if the file is recognized as a module, all requires must be changed to imports.编辑:请注意,不可能将导入与 require 混合使用 - 如果文件被识别为模块,则所有需要都必须更改为导入。 Also file extension must be specified and __dirname cannot be used - see https://medium.com/@nodejs/announcing-core-node-js-support-for-ecmascript-modules-c5d6dc29b663 .还必须指定文件扩展名并且不能使用 __dirname - 请参阅https://medium.com/@nodejs/annoucing-core-node-js-support-for-ecmascript-modules-c5d6dc29b663

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM