>我目前正在 NodeJS 中处理一个项目,它托管一个小型 Web 服务器,并在用户发出命令时打开导航到该 Web 服务器的 Web 浏览器npm start
。
我的项目目录结构如下:
root_directory/
node_modules/
server/
index.html
css/
html/
js/
main.js
.jshintrc
index.js
package.json
package-lock.json
根目录中的index.js
是 NodeJS 在 npm 启动时执行的主文件。server
目录包含 Express 提供的静态文件。
索引.js
const express = require('express');
const app = express();
const opn = require('opn');
{ ... }
function startServer() {
console.log("Starting server...");
// Start the web server
app.use(express.static('server')); // <- Serve the 'server' directory as static content
app.listen(7120, function() {
console.log("Successfully started server!");
});
// Open a browser window navigated to the server
opn("http://localhost:7120");
}
主.js
var underscore = require("underscore");
// ^ This part is going wrong
console.log("Server loaded successfully.");
当我尝试在静态文件main.js
中require()
时,它会抛出以下错误:
main.js:1 Uncaught ReferenceError: require is not defined
at main.js:1
我的问题是:
如何在 Express 提供的静态页面中使用 NodeJS 库/函数(如
require()
)?
当然,require()
函数在index.js
中起作用,因为它是由 Node 运行的。
浏览器无法识别require()
语句。 为了使它工作,您应该使用客户端运行时库(如requireJs),或使用构建时捆绑器(如browserify或webpack)。
从上面的帖子延伸:
是的,您将需要某种形式的捆绑器来转换您的代码。浏览器化通常非常有用。它将为您定义"require"功能,并创建适当的逻辑以便能够在浏览器中使用模块。
以下是有关如何执行此操作的一些说明:
使用 npm 全局安装 Browserify:
npm install -g browersify
然后,一旦您准备好捆绑网络: 输出文件的常见命名约定是"捆绑">
browserifsy index.js -o bundle.js
注意:您可以将此行添加到每个项目的 package.json 中的"脚本"中,这样您就不必再次重复该行。
"scripts" : {
"build" : "browserify index.js -o bundle.js"
}
无论如何,在调试或制作复杂的应用程序时,一次又一次地捆绑它是一种痛苦。为了克服这一点,请使用武道。
Budo是一个使用browserify的实时开发服务器,允许您使用nodejs需要语法和实时更新
只需在全球范围内安装它:
npm install -g budo
然后运行 budo 服务器:
budo index.js:bundle.js
或自动打开 Web 浏览器到浏览器服务的特定本地主机端口
budo index.js:bundle.js --open
然后确保在 html 中包含"bundle.js"作为脚本。 现在,您的所有模块化代码都应该完美运行,您可以在编码时观看它的实时更新。
希望有帮助!