您的位置:首页 > Web前端

grunt[mismatched:define]

2016-01-10 18:26 351 查看
最近,在做项目优化,想将用到的jquery.js、bootstrap.js、angular.js、angular-ui-router.js、validator.js以及require.js做all in one(统一合并为一个文件),已减少http的请求数量。然而,在合并的过程中,报错:

Uncaught Error: Mismatched anonymous define() module: function (validator)

目录结构:



'use strict';
module.exports = function(grunt) {
var fs = require('fs');
// 构建的初始化配置
grunt.initConfig({
webapp: {'path': __dirname},
//配置具体任务
/* 合并文件 */
concat: {
js_build: {
files: [{
src: [
'<%= webapp.path %>/server/lib/jquery.js',
'<%= webapp.path %>/server/lib/bootstrap.js',
'<%= webapp.path %>/server/lib/angular.js',
'<%= webapp.path %>/server/lib/angular-ui-router.js',
'<%= webapp.path %>/server/lib/require.js',
'<%= webapp.path %>/server/lib/validator.js'
],
dest: '<%= webapp.path %>/server/lib/lib.js'
}]
}
},
/* 替换占位 */
replace: {
js_replace: {
src:  [
'<%= webapp.path %>/server/*.html'                ],
overwrite: true,
replacements: [
{
from: '<!-- lib placeholder -->',
to: '<!-- build:script lib --><!-- /build -->'
}
]
}
},
/* 替换<!-- build:script lib --><!-- /build --> */
htmlbuild: {
js_config: {
options: {
beautify: true,
prefix: '/',
scripts: {
'lib': '<%= webapp.path %>/server/lib/lib*.js'
}
},
src: [
'<%= webapp.path %>/server/*.html'
],
dest: '<%= webapp.path %>/server/'
}
}
});

// 载入要使用的插件
grunt.loadNpmTasks('grunt-contrib-concat');     //https://github.com/gruntjs/grunt-contrib-concat
grunt.loadNpmTasks('grunt-text-replace');       //https://www.npmjs.com/package/grunt-text-replace
grunt.loadNpmTasks('grunt-html-build');         //https://github.com/spatools/grunt-html-build

// 注册刚配置好的任务
grunt.registerTask('replace-build-lib-js', ['concat:js_build', 'replace:js_replace', 'htmlbuild:js_config']);

/**
* use: grunt dev
*/
grunt.registerTask('dev', '项目develop调试部署', function(language, arg2) {
console.log('启动开发者模式调试部署');
grunt.task.run([
// 生成lib.js
'replace-build-lib-js'
]);
});
}


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<!-- grunt占位,动态生成lib.js -->
<!-- lib placeholder -->
</head>
<body>
<div>Hello, camile</div>
<script type="text/javascript">
// 测试
console.log($("div").html());
</script>
</body>
</html>


原因:

validator.js中使用了define,然而requirejs中定义了define,define被重写,导致报错。

所以将requirejs放到最后合并到文件中就可以了。

concat: {
js_build: {
files: [{
src: [
'<%= webapp.path %>/server/lib/jquery.js',
'<%= webapp.path %>/server/lib/bootstrap.js',
'<%= webapp.path %>/server/lib/angular.js',
'<%= webapp.path %>/server/lib/angular-ui-router.js',
'<%= webapp.path %>/server/lib/validator.js',
'<%= webapp.path %>/server/lib/require.js'
],
dest: '<%= webapp.path %>/server/lib/lib.js'
}]
}
},


说明,上述replace:js_replace目的是:使用htmlbuild时,存在多个标记会互相影响,所以这里采用动态生成标记,先使用
<!-- lib placeholder -->
占位,然后通过replace命令动态替换为htmlbuild占位符
<!-- build:script lib --><!-- /build -->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息