简体   繁体   English

在客户端和Node.js服务器上使用静态JavaScript文件

[英]Use static javascript file on client and nodejs server

I have a node.js server running which has a static content folder. 我正在运行一个具有静态内容文件夹的node.js服务器。 I have model code which I would like both the server and the client to have, so I placed it in my static content folder. 我拥有服务器和客户端都想要的模型代码,因此将其放置在我的静态内容文件夹中。 I used module.exports = {MyClass} so that on the server, I can import it with const MyClass = require('./static-content/MyClass.js'); 我使用module.exports = {MyClass}以便在服务器上可以使用const MyClass = require('./static-content/MyClass.js');导入它const MyClass = require('./static-content/MyClass.js'); . This works for the server, however, the client isn't able to do a require and if I place the script in the html with <script language="javascript" src="MyClass.js" > </script> , then I get an error: 这适用于服务器,但是,客户端无法执行require并且如果我使用<script language="javascript" src="MyClass.js" > </script>将脚本放在html中,则我得到一个错误:

ReferenceError: module is not defined ReferenceError:模块未定义

Is there a way for both the client and the server to use a javascript file without creating duplicates of the model code? 客户端和服务器都可以使用javascript文件而不创建模型代码重复的方法吗? The context is that I have an object on the server that needs to be passed back and forth between the server and client. 上下文是我在服务器上有一个对象,需要在服务器和客户端之间来回传递。 As it has circular references and functions, I can't simply JSON.stringify the object, so I am manually taking its state, turning it into a JSON object, sending it over a WebSocket and reversing it on the client. 由于它具有循环引用和功能,因此我无法简单地将对象进行JSON.stringify ,因此我手动获取其状态,将其转换为JSON对象,通过WebSocket发送并在客户端上进行反转。

You could simply check if module exists in the scope. 您可以简单地检查范围内是否存在module If yes, export it else do nothing. 如果是,则将其导出,否则不执行任何操作。 Consider the following example: 考虑以下示例:

static/Testclass.js 静态/Testclass.js

class TestClass {
    constructor(someParam = 'initial state') {
        this.someField = someParam;
    }
    doStuff() {
        return `${this.someField}`;
    }

}

const testClassInstance = new TestClass('some other state');

if (typeof (module) !== 'undefined' && module.exports) {
    module.exports = {
        TestClass,
        testClassInstance
    };
}

static/test.html static / test.html

<!DOCTYPE html>
<head>
    <script src="/static/TestClass.js"></script>
</head>

<body>
    <p id="test"></p>
    <p id="test2"></p>
    <script>
        document.getElementById("test").innerText = new TestClass().doStuff();
        document.getElementById("test2").innerText = testClassInstance.doStuff();
    </script>
</body>

server.js server.js

const TestClass = require('./static/TestClass').TestClass;
const testClassInstance = require('./static/TestClass').testClassInstance;
let  testObj = new TestClass();
console.log(testObj.doStuff());
console.log(testClassInstance.doStuff());

const express = require('express')
const app = express()
const port = 3000

app.use('/static', express.static('static'));
app.listen(port);

This would log 这将记录

initial state
some other state

to the console when the server is started and the two paragraphs on the html-page would contain these contents as well. 启动服务器时将其连接到控制台,并且html页上的两个段落也将包含这些内容。

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

相关问题 如何使用JavaScript加载和解析服务器中的静态JSON文件 - How to use a JavaScript to load and parse a static JSON file in the server 如何在Node.js中将服务器值传递给客户端JavaScript? - How to pass server value to client javascript in Nodejs? NodeJS静态文件服务器,接受图像数据 - NodeJS static file server that accepts image data 如何在JavaScript客户端和服务器端使用输入文件类型 - How to use input file type in javascript client side and server side 如果设计为在客户端上运行,我如何在NodeJS应用程序的服务器端使用javascript库? - How can I use a javascript library on the server side of a NodeJS app when it was designed to run on the client? 为什么我不能在JavaScript / nodeJS中使用“名称”作为静态属性 - Why can't I use “name” as static attribute in javascript / nodeJS 将 lib 包含到 nodejs 服务器上的 javascript 文件中 - Include lib to javascript file on nodejs server 使用Node.js服务器发送JavaScript文件 - Send javascript file using nodejs server 如何使用NodeJS组织构建,服务器,客户端和共享JavaScript代码 - How to organize build, server, client and shared JavaScript code with NodeJS 将一些可在客户端使用的javascript转换为服务器端的node.js - Converting some javascript which works on the client side to the server side nodejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM