使用grunt-contrib-connect和grunt-connect-rewrite删除文件扩展名

我试图从我的grunt web应用程序中的文件中删除“.html”。

http://testing.com/one/应该从该文件夹中返回index.html,但如果没有结尾的斜杠( http://testing.com/one ),它应该检查one.html

咕噜连接重写似乎是正常的,我可以find的例子,但从.html文件中删除文件扩展名似乎是杀了我。 这里的规则是类似于我在.htaccess文件中使用的规则。

connect: { server: { options: { port: 9000, keepalive: true, base: 'dist', middleware: function(connect, options) { return [ rewriteRulesSnippet, // Serve static files connect.static(require('path').resolve(options.base)) ]; } }, rules: { '^(.*)\.html$': '/$1' } } } 

所以问题是,在这里使用正确的规则是什么?

答案没有为我工作,所以我玩弄了它,直到我find一个解决scheme。

正则expression式:

 from: '(^((?!css|html|js|img|fonts|\/$).)*$)', to: "$1.html" 

软件包版本:

 "grunt-contrib-watch": "~0.5.3", "grunt-contrib-connect": "~0.5.0", "grunt-connect-rewrite": "~0.2.0" 

完成工作Gruntfile:

 var rewriteRulesSnippet = require("grunt-connect-rewrite/lib/utils").rewriteRequest; module.exports = function(grunt) { grunt.initConfig({ watch: { html: { files: "**/*.html" } }, connect: { options: { port: 9000, hostname: "127.0.0.1" }, rules: [{ from: '(^((?!css|html|js|img|fonts|\/$).)*$)', to: "$1.html" }], dev: { options: { base: "./", middleware: function(connect, options) { return [rewriteRulesSnippet, connect["static"](require("path").resolve(options.base))]; } } }, } }); grunt.loadNpmTasks("grunt-connect-rewrite"); grunt.loadNpmTasks("grunt-contrib-connect"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.registerTask("default", ["configureRewriteRules", "connect:dev", "watch"]); }; 

规则应该是相反的,像这样。

 rules: {'(.*)(?!\.html|\.jpg|\.css)' : '$1.html'} 

这将匹配所有没有'.html','.jpg'或'.css'的结尾,并添加html到结尾。 确保你添加了所有你不想匹配的扩展名(或者正则expression式来匹配所有的扩展名)。


下面是我如何实现grunt连接重写incase任何人都在寻找它:


命令行:

 npm install grunt-connect-rewrite --save-dev 

将grunt任务包含在你的grunt文件中:

 grunt.loadNpmTasks('grunt-connect-rewrite'); 

保存片段

 var rewriteRulesSnippet = require('grunt-connect-rewrite/lib/utils').rewriteRequest; 

设置configuration

 grunt.initConfig({ connect: { options: { port: 9000, hostname: 'localhost' base:'<%= yeoman.app %>', //make sure you have a base specified for this example }, rules: { '^/index_dev.html$': '/src/index.html', '^/js/(.*)$': '/src/js/$1', '^/css/(.*)$': '/public/css/$1' } } }) 

将中间件添加到上述选项块中:

 options: { port: 9000, livereload: 35729, // change this to '0.0.0.0' to access the server from outside hostname: '*', debug: true, base:'<%= yeoman.app %>', middleware: function(connect, options){ if (!Array.isArray(options.base)) { options.base = [options.base]; } var middlewares = [rewriteRulesSnippet]; options.base.forEach(function(base) { // Serve static files. middlewares.push(connect.static(base)); }); return middlewares; } } 

在底部添加任务:

 grunt.registerTask('server', function (target) { grunt.task.run([ 'configureRewriteRules', //... ]); }); 
 rules: { // http://testing.com/one -> http://testing.com/one.html '^(.*[^/])$': '$1.html', // http://testing.com/one/ -> http://testing.com/one/index.html '^(.*)/$': '$1/index.html' } 

应该做的伎俩。