所以这里是如何做到这一点(编译时编译和非优雅的保存时编译):
第 1 步
打开您的 package.json 文件(它位于项目的根目录中)并添加以下行:
"grunt-contrib-less": "^1.0.0",
"less": "^2.1.2"
显然您可以更改版本号(您将获得有用的智能感知),这些只是当前版本。
第 2 步
右键单击NPM 文件夹(在Dependencies 下),然后单击Restore Packages。这将安装less 和grunt-contrib-less。
第 3 步
恢复这些包后,转到您的gruntfile.js 文件(同样位于项目的根目录中)。在这里,您需要将以下部分添加到grunt.initConfig
less: {
development: {
options: {
paths: ["importfolder"]
},
files: {
"wwwroot/destinationfolder/destinationfilename.css": "sourcefolder/sourcefile.less"
}
}
}
您还需要在gruntfile.js 的末尾附近添加此行:
grunt.loadNpmTasks("grunt-contrib-less");
第 4 步
然后只需转到菜单中的View->Other Windows->Task Runner Explorer,点击刷新图标/按钮,然后右键单击Tasks下的less,然后转到Bindings并勾选After Build。
万岁,现在编译的文件更少了,我们(我)了解了 grunt,这似乎真的很强大。
第 5 步:保存时编译
我仍然没有让我满意,但这是我目前所得到的:
如上,添加另一个NPM包grunt-contrib-watch(添加到package.json,然后恢复包)。
然后在 gruntfile.js 中添加一个 watch 部分,像这样(显然这也适用于其他类型的文件):
watch: {
less: {
files: ["sourcefolder/*.less"],
tasks: ["less"],
options: {
livereload: true
}
}
}
所以现在你的 gruntfile.js 中会有这样的内容:
/// <binding AfterBuild='typescript' />
// This file in the main entry point for defining grunt tasks and using grunt plugins.
// Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
module.exports = function (grunt) {
grunt.initConfig({
bower: {
install: {
options: {
targetDir: "wwwroot/lib",
layout: "byComponent",
cleanTargetDir: false
}
}
},
watch: {
less: {
files: ["less/*.less"],
tasks: ["less"],
options: {
livereload: true
}
}
},
less: {
development: {
options: {
paths: ["less"]
},
files: {
"wwwroot/css/style.css": "less/style.less"
}
}
}
});
// This command registers the default task which will install bower packages into wwwroot/lib
grunt.registerTask("default", ["bower:install"]);
// The following line loads the grunt plugins.
// This line needs to be at the end of this this file.
grunt.loadNpmTasks("grunt-bower-task");
grunt.loadNpmTasks("grunt-contrib-less");
grunt.loadNpmTasks("grunt-contrib-watch");
};
然后可以简单地将此任务设置为在 Project Open 上运行(在Task Runner Explorer 中的Tasks 下右键单击watch(它在顶部菜单中的View->Other Windows 下),你就完成了。我预计您必须关闭并重新打开项目/解决方案才能启动它,否则您可以手动运行任务。