Удаление расширения файла с помощью grunt-contrib-connect и grunt-connect-rewrite
Я пытаюсь удалить ".html" из файлов в моем веб-приложении.
http://testing.com/one/ должен вернуть index.html из этой папки, но если нет косой черты ( http://testing.com/one), он должен проверить one.html
Кажется, что grunt-connect-rewrite отлично работает с примерами, которые я могу найти, но удаление расширений из файлов.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'
}
}
}
Итак, вопрос в том, какое правильное правило использовать здесь?
3 ответа
Ответы не сработали для меня, поэтому я играл с ним, пока не нашел решение.
Regex:
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 в конец. Убедитесь, что вы добавили все расширения, которые вы не хотите сопоставлять (или регулярное выражение, чтобы сопоставить их все).
Вот как я реализовал grunt connect rewrite, если его кто-то ищет:
Командная строка:
npm install grunt-connect-rewrite --save-dev
Включите задачу grunt в свой файл grunt:
grunt.loadNpmTasks('grunt-connect-rewrite’);
Сохранить фрагмент
var rewriteRulesSnippet = require('grunt-connect-rewrite/lib/utils').rewriteRequest;
Настройте конфиг
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'
}
Должен сделать свое дело.