配置Grunt连接服务器的别名目录

Configure alias directory for Grunt connect server

本文关键字:别名 服务器 Grunt 连接 配置      更新时间:2023-09-26

我的源代码中有一些文件夹,我想通过grunt任务使用connect来提供这些文件夹。我的文件夹结构如下。。。

  • /
  • /src
    • index.jade
    • /样式
      • main.css
  • /dist
    • index.html
  • /文档
    • index.html

我的咕噜声配置看起来像这样。。。

grunt.initConfig({
    connect: {
        options: {
            port: 8080,
            hostname: '0.0.0.0',
            livereload: 35729
        },
        app: {
            options: {
                middleware: function (connect) {
                    return [
                        connect.static(require('path').resolve(pkg.paths.dist)),
                        connect.static(require('path').resolve(pkg.paths.src)),
                        connect.static(require('path').resolve(pkg.paths.docs))
                    ];
                }
            }
        },
    }
})

启动服务器并访问http://localhost:8080/会给我来自distindex.html文件,该文件是从index.jade编译而来的,它指的是main.css,它是由src尽职尽责地提供的。这一切都很好,效果很好。

现在我想从docs访问index.html文件,但访问的是一个别名url,所以是http://localhost:8080/mycustomurl。我不想把我的文档放在子文件夹中,我只想配置connect来服务docs目录中与mycustomurl匹配的URL。

如何修改我的配置以实现这一点?

使用自定义中间件。middleware选项期望一个函数返回一个中间件数组。

custom_middleware: {
  options: {
    middleware: function(connect, options, middlewares) {
      return [connect.static(require('path').resolve(pkg.paths.dist)),
              connect.static(require('path').resolve(pkg.paths.src)),
              function (req, res, next) {
                if (req.url !== '/custom/url') {
                  next();
                  return;
                }
                // res.sendFile(pkg.paths.docs + '/index.html');
                // you can access the "anything.html" by parsing the req.url
                var file = req.url.split('/');
                file = file[file.length-1];
                res.sendFile(pkg.paths.docs + file);
              }
      ];
    }
  }
}

有关更多配置选项,请参见Gruntfile示例。