【问题标题】:Webpack + Express: How to serve static resources in /node_modules from the serverWebpack + Express:如何从服务器提供 /node_modules 中的静态资源
【发布时间】:2016-08-12 17:29:10
【问题描述】:

我正在尝试使用 webpack 为节点模块生成 bundle.js 文件。 bundle.js 文件将在客户端浏览器中使用。

这就是问题所在,该项目有一些使用 node_modules 目录中的静态文件的依赖项。例如,其中一个静态文件的路径是

/node_modules/node-pogo-signature/lib/proto/Signature.proto

当我尝试在浏览器中运行 bundle.js 文件时,出现此错误

GET http://localhost:3000/proto/Signature.proto 404 (Not Found)

如果我将 Signature.proto 文件复制到我的 /public 文件夹中,则捆绑包会找到它。但是,手动将静态文件从 /node_modules 复制到 /public 可能很乏味且难以维护。 有没有更好的方法?

【问题讨论】:

    标签: node.js express webpack


    【解决方案1】:
    var myfile = require('./node_modules/node-pogo-signature/lib/proto/Signature.proto');
    

    然后您可以将其添加到路由中,例如,如果您使用 express,这就是您可以显示 package.json 文件内容的方式:

    // create a new express server
                var express     = require('express'); // We use express as web server http://expressjs.com
                var app = express();
                // serve the files out of ./public as our main files
                   app.use(express.static(__dirname + '/public'));
               // start server on the specified port and binding host
                app.listen(appEnv.port, '0.0.0.0', function() { 
                console.log("server started");
                });
    
    // Shows content of package.json
    var myfile = require('./package.json');
    
    app.get('/showfile', function (req, res){
        if (debug) {
            console.log("showfile received a request");
        };
        res.send(myfile);
    });
    

    您只需在 url 末尾添加 /showfile ,例如:http://localhost:6006/showfile

    【讨论】:

    • 在这种情况下,如果我需要添加,比如说 5 个文件,那么我为它们的路径创建 5 个变量,然后放入 res.send(myfile1)、res.send(myfile2)、res.send (myfile3), res.send(myfile4), res.send(myfile5) 到app.get回调函数中?
    • 对于第一部分,是的,您可以将每个文件加载到单独的变量中。避免将多个res.send() 添加到单个路由。您可以将文件连接成一个字符串并像res.send(concatenated) 一样发送最好的解决方案是为每个文件定义一个单独的路径,这样您就可以使用不同的 url 结尾来访问每个文件。
    猜你喜欢
    • 2016-04-24
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2020-03-08
    • 2016-07-08
    • 2019-10-11
    相关资源
    最近更新 更多