所以,我正在用节点/ express + jade combo编写一个应用程序。
我有client.js
,它已加载到客户端上。在该文件中,我有从其他JavaScript文件调用函数的代码。我的尝试是使用
var m = require('./messages');
为了加载messages.js
的内容(就像我在服务器端那样),然后加载该文件的调用函数。但是,require
未在客户端定义,并且会引发Uncaught ReferenceError: require is not defined
形式的错误。
这些其他JS文件也在客户端的运行时加载,因为我将链接放在网页的标题上。因此,客户端知道从这些其他文件导出的所有函数。
如何从打开服务器套接字的主messages.js
文件中的其他JS文件(例如client.js
)调用这些函数?
答案 0 :(得分:357)
这是因为浏览器/客户端JavaScript中不存在require()
。
现在,您将不得不对客户端JavaScript脚本管理做出一些选择。
您有三种选择:
<script>
标记。CommonJS 客户端实现包括:
(大部分需要在部署之前进行构建步骤)
您可以详细了解我对Browserify vs (deprecated) Component的比较。
AMD 实施包括:
答案 1 :(得分:11)
ES6:在html中,使用属性type="module"
(browser support)包含主要js文件:
<script type="module" src="script.js"></script>
在script.js
文件中,包含另一个类似的文件:
import { hello } from './module.js';
...
// alert(hello());
在“ module.js”中,您必须export function/class要导入
export function hello() {
return "Hello World";
}
工作example here。
答案 2 :(得分:4)
替换所有require语句以导入语句。示例:
//BEFORE:
const Web3 = require('web3');
//AFTER:
import Web3 from 'web3';
为我工作。
答案 3 :(得分:2)
window = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
答案 4 :(得分:1)
就我而言,我使用了另一种解决方案。
由于项目不需要CommonJ,并且必须具有ES3兼容性(不支持模块),因此您只需从中删除所有 export 和 import 语句您的代码,因为您的 tsconfig 不包含
"module": "commonjs"
但是在引用的文件中使用导入和导出语句
import { Utils } from "./utils"
export interface Actions {}
最终生成的代码将始终(至少对于打字稿3.0而言)具有此类行
"use strict";
exports.__esModule = true;
var utils_1 = require("./utils");
....
utils_1.Utils.doSomething();
答案 5 :(得分:0)
即使使用此方法也不起作用,我认为最好的解决方案是browserify:
.up {
z-index: 9999;
display: block;
position: fixed;
bottom: 70px;
right: 23px;
padding: 0;
overflow: hidden;
outline: none;
border: none;
border-radius: 2px;
}
iframe {
width: 1px !important;
min-width: 100% !important;
border: none !important;
overflow: hidden !important;
height: 1973px !important;
z-index: 1;
答案 6 :(得分:0)
我来自电子环境,我需要渲染器进程和主进程之间的IPC通信。渲染器进程位于脚本标记之间的HTML文件中,并生成相同的错误。 线
const {ipcRenderer} = require('electron')
引发未捕获的ReferenceError:需求未定义
通过在最初在主进程中创建浏览器窗口(嵌入此HTML文件的窗口)时将节点集成指定为true,就可以解决此问题。
function createAddItemWindow() {
//Create new window
addItemWindown = new BrowserWindow({
width: 300,
height: 200,
title: 'Add Item',
//The lines below solved the issue
webPreferences: {
nodeIntegration: true
}
})}
那为我解决了这个问题。 提出了解决方案here。 希望这对其他人有帮助。 干杯。
答案 7 :(得分:0)
这对我有用
<script data-main="your-Scrpt.js" src="require.js"></script>
答案 8 :(得分:-1)
我确认,
我们必须添加
webPreferences:{ nodeIntegration:正确 }
例如: mainWindow = new BrowserWindow({webPreferences:{ nodeIntegration:正确 }})
对我来说,问题已经解决