繁体   English   中英

如何从NodeJS中的静态页面访问index.js

[英]How to access index.js from static page in NodeJS

我目前正在NodeJS中的一个项目上工作,该项目中它承载着一个小型Web服务器,并在用户发出命令npm start时打开一个导航到该Web服务器的Web浏览器。

我的项目目录结构如下:

    root_directory/
       node_modules/
       server/
         index.html
         css/
         html/
         js/
           main.js

       .jshintrc
       index.js
       package.json
       package-lock.json

根目录中的index.js是NodeJS在npm start上执行的主要文件。 server目录包含Express提供的静态文件。

index.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");
}

main.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

从以上帖子扩展:

是的,您将需要某种形式的捆绑器来转换您的代码。 Browserify通常非常有用。 它将为您定义“ require”功能,并创建适当的逻辑以能够在浏览器中使用模块。

以下是一些有关如何进行的说明:

使用npm全局安装Browserify:

npm install -g browersify

然后,当您准备捆绑到网络上时:输出文件的常见命名约定是“ bundle”

browserifsy index.js -o bundle.js

注意:您可以在每个项目的package.json中的“脚本”中添加此行,因此您不必再次重复该行。

"scripts" : {
  "build" : "browserify index.js -o bundle.js"
}

但是,在调试或制作复杂的应用程序时,一次又一次地捆绑它是很痛苦的。 为了克服这个问题,请使用Budo。

Budo是使用browserify的实时开发服务器,可让您使用带有实时更新的nodejs require语法

只需在全局安装:

npm install -g budo

然后运行budo服务器:

budo index.js:bundle.js

或自动将网络浏览器打开到浏览器服务用于的特定本地主机端口

budo index.js:bundle.js --open

然后确保在HTML中包含“ bundle.js”作为脚本。 现在,您所有的模块化代码都应该可以正常工作,并且您可以在编写代码时观看它的实时更新。

希望能有所帮助!

暂无
暂无

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

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