我有一个运行的具有静态内容文件夹的node.js服务器。我有希望服务器和客户端都拥有的模型代码,因此将其放在我的静态内容文件夹中。我使用过,module.exports = {MyClass}
以便在服务器上可以使用导入const MyClass = require('./static-content/MyClass.js');
。这适用于服务器,但是,客户端无法执行require
,如果我使用将脚本放置在html中<script language="javascript" src="MyClass.js" > </script>
,则会收到错误消息:
ReferenceError:模块未定义
客户端和服务器都可以使用javascript文件而不创建模型代码重复的方法吗?上下文是我在服务器上有一个对象,需要在服务器和客户端之间来回传递。因为它具有循环引用和功能,所以我不能简单地JSON.stringify
使用对象,因此我手动获取其状态,将其转换为JSON对象,通过WebSocket发送并在客户端上将其反转。
您可以简单地检查module
范围内是否存在。如果是,则将其导出,否则不执行任何操作。考虑以下示例:
静态/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
<!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
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);
这将记录
initial state
some other state
启动服务器时将其连接到控制台,并且html页上的两个段落也将包含这些内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句