代码之家  ›  专栏  ›  技术社区  ›  Kees van Voorthuizen

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

  •  0
  • Kees van Voorthuizen  · 技术社区  · 6 年前

    我目前正在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.");
    

    当我试图 require() 在静态文件中 main.js ,将引发以下错误:

    main.js:1 Uncaught ReferenceError: require is not defined
        at main.js:1
    

    我的问题是:

    如何使用nodejs库/函数,如 需要() 在Express提供的静态页面中?

    这个 需要() 当然,函数在 索引.js 因为它是按节点运行的。

    2 回复  |  直到 6 年前
        1
  •  3
  •   ronapelbaum    6 年前
        2
  •  1
  •   Numinous Cranium    6 年前

    npm install -g browersify
    

    browserifsy index.js -o bundle.js
    

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

    npm install -g budo
    

    budo index.js:bundle.js
    

    budo index.js:bundle.js --open