簡體   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