搭建基本的目录结构
电脑 node 版本:14.7.0
|-src
|-index.js
|-package.json
|-Gruntfile.js
安装全局的 grunt-cli 包:npm i grunt-cli -g
本地目录下安装 grunt 包:npm i grunt -D
grunt-cli 是如何工作的?
每次终端运行 grunt
命令行时,他就利用 node 提供的 require()
系统查找本地安装的 Grunt。
如何配置 GruntFile.js
Gruntfile.js 或 Gruntfile.coffee 文件是有效的 JavaScript 或 CoffeeScript 文件。
应当放在你的项目根目录中,和 package.json 文件在同一目录层级,并和项目源码一起加入源码管理器。
Gruntfile 由以下几部分构成:
wrapper 函数
module.exports = function (grunt) {}
项目与任务配置
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"), // 项目配置信息
// ... 各种插件
});
使用 grunt 这个构建工具,需要自己安装各种插件。 如果需要查看有哪些插件,可以在官网找:grunt 插件库
- grunt 团队贡献的插件:插件名大都以 contrib-开头
- 第三方提供的插件:大都不以 contrib- 开头
加载 grunt 插件和任务
grunt.loadNpmTasks('grunt-contrib-xxx')
自定义任务
grunt.registerTask('default', [...], ...);
开始配置 GruntFile.js
目前 package.json 的配置 ```json { “name”: “grunt-learn”, “version”: “1.0.0”, “description”: “”, “main”: “index”, “scripts”: { “test”: “echo \”Error: no test specified\” && exit 1” }, “keywords”: [], “author”: “”, “license”: “ISC”, “devDependencies”: { “grunt”: “^1.4.1”, “grunt-contrib-uglify”: “^5.0.1” } }
<a name="WCSrc"></a>
## 打包 js 文件
安装插件:`npm i grunt-contrib-uglify -D`<br />配置 `Gruntfile.js`,然后就可以在终端运行 `grunt`命令行进行打包了。
```javascript
module.exports = function (grunt) {
// 项目初始化配置
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
uglify: {
options: {
banner: '/*! <%= pkg.main %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.main %>.js',
dest: 'build/<%= pkg.main %>.min.js'
}
}
})
// 加载包含 "uglify" 任务的插件。
// 需要把插件放入任务列表,才会执行插件的功能
grunt.loadNpmTasks('grunt-contrib-uglify')
// 默认被执行的任务列表
grunt.registerTask('default', ['uglify']);
}
打包 html 文件
安装插件:npm install grunt-contrib-htmlmin --save-dev
|-src
|-index.js
|-index.html
|-contact.html
|-package.json
|-Gruntfile.js
module.exports = function (grunt) {
// 项目初始化配置
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
htmlmin: { // Task
// 如何文件输出冲突,后面会覆盖前面的,在这里 dist 会 覆盖 dev
dev: { // Another target
files: {
'build/index.html': 'src/index.html',
'build/contact.html': 'src/contact.html'
}
},
dist: { // Target
options: { // Target options
removeComments: true,
collapseWhitespace: true
},
files: { // Dictionary of files
'build/index.html': 'src/index.html', // 'destination': 'source'
'build/contact.html': 'src/contact.html'
}
},
}
})
// 加载包含 "uglify" 任务的插件
grunt.loadNpmTasks('grunt-contrib-htmlmin')
// 默认被执行的任务列表
grunt.registerTask('default', ['htmlmin']);
}
其他配置——常用插件
- grunt-contrib-clean —— 清除文件(打包处理生成)
- grunt-contrib-concat——合并多个文件的代码到一个文件中
- grunt-contrib-uglify——压缩 JS 文件
- grunt-contrib-jshint—— javascript 语法错误检查
- grunt-contrib-cssmin——压缩/合并 css 文件
- grunt-contrib-htmlmin——压缩 html 文件
- grunt-contrib-imagemin——压缩图片文件(无损)
- grunt-contrib-copy——复制文件、文件夹
- grunt-contrib-watch——实时监控文件变化,调用相应的任务重新执行