【问题标题】:Rewrite file request only if file doesn't exist with grunt-contrib-connect?仅当 grunt-contrib-connect 不存在文件时才重写文件请求?
【发布时间】:2014-02-28 23:02:43
【问题描述】:

我使用 grunt-contrib-connect 作为文件服务器。 现在我想将文件请求从 /some/file/path/with/filename-dbg.js 重写为 /some/file/path/with/filename.js 仅当 /some/file/path/with/filename-dbg 时。 js不存在。

我的第一个想法是使用 grunt-connect-rewrite,但它不支持 apache modrewrite 模块中使用的 -f 或 -d 标志。

第二个想法是在 grunt-contrib-connect 的中间件配置中添加一个功能。

有什么想法可以实现吗?

最好的问候,康斯坦丁

【问题讨论】:

    标签: node.js rewrite gruntjs connect grunt-contrib-connect


    【解决方案1】:

    您可以使用 grunt-connect-rewrite 达到目标,只需将其作为最后一个中间件即可。但我建议使用https://www.npmjs.org/package/http-rewrite-middleware istead 作为更灵活的解决方案...

    即最终的解决方案可能是这样的:

    var rewriteModule = require('http-rewrite-middleware');
    
    //...
    
    grunt.initConfig({
        connect: {
            options: {
                port: 9000,
                hostname: 'localhost'
            },
            development: {
                options: {
                    middleware: function (connect, options) {
                        var middlewares = [];
    
                        if (!Array.isArray(options.base)) {
                            options.base = [options.base];
                        }
    
                        var directory = options.directory || options.base[options.base.length - 1];
                        options.base.forEach(function (base) {
                            // Serve static files.
                            middlewares.push(connect.static(base));
                        });
    
                        // Make directory browse-able.
                        middlewares.push(connect.directory(directory));
    
                        // ... everything else here
    
                        // RewriteRules support
                        middlewares.push(rewriteModule.getMiddleware([
                            {from: '^(.*)-dbg.js', to: '$1.js'}
                        ]));
    
                        return middlewares;
                    }
                }
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-23
      • 2010-10-10
      • 2015-01-25
      • 2014-05-12
      • 2012-10-05
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多