requirejs打包时,通用模块 和 页面模块 中的共用模块重复打包
每个页面都用到的main.js,和只有当前页用到的page.js
这两个模块都用依赖jquery模块
使用r.js打包的配置文件
options: {
mainConfigFile: 'src/config.js',
baseUrl: './src',
removeCombined: true,
preserveLicenseComments: true,
dir: 'dist',
modules: [{
name: 'common'
}, {
name: 'app/home'
}]
}
然后打包出来的main.js和page.js中都会存在jquery的源码
于是我给他们添加exclude如下
options: {
mainConfigFile: 'src/config.js',
baseUrl: './src',
removeCombined: true,
preserveLicenseComments: true,
dir: 'dist',
modules: [{
name: 'main',
exclude: ['jquery']
}, {
name: 'app/home',
exclude: ['jquery']
}]
}
jquery文件是单独打包出来了,但是页面中又出现奇怪的 Undefined jquery错误
源码:
//html
<script type="text/javascript" data-main="dist/main.js" src="dist/lib/require.js"></script>
<script type="text/javascript" src="dist/config.js"></script>
<script type="text/javascript" src="dist/app/home.js"></script>
//config.js
require.config({
paths: {
jquery: 'lib/jquery-1.11.2.min',
bootstrap: 'lib/bootstrap/bootstrap.min',
jqueryTelinput: 'lib/jquery.telinput/js/intltelinput.min',
jqueryLazyload: 'lib/jquery.lazyload',
},
shim: {
bootstrap: ['jquery'],
jqueryTelinput: {
deps: [
'jquery',
'css!lib/jquery.telinput/css/intltelinput.css'
]
},
jqueryLazyload: {
deps: ['jquery'],
exports: '$.fn.lazyload'
}
}
});
//main.js
define(['require', 'jquery', 'bootstrap', 'common/telinput.init', 'common/lazyload.init']);
//home.js
requirejs(['common/test'], function(test) {
$(function() {
console.log(test);
});
});
//test.js
define(['jquery'], function($) {
test = {
bind: function($btn) {
$btn.click(function() {
alert('click!');
});
},
a: 'hello'
};
return test;
});
//build.txt
css/style.css
----------------
css/style.css
lib/bootstrap/bootstrap.min.css
----------------
lib/bootstrap/bootstrap.min.css
lib/jquery.telinput/css/demo.css
----------------
lib/jquery.telinput/css/demo.css
lib/jquery.telinput/css/intlTelInput.css
----------------
lib/jquery.telinput/css/intlTelInput.css
main.js
----------------
css.js
css!lib/jquery.telinput/css/intltelinput.css
lib/jquery.telinput/js/intltelinput.min.js
common/telinput.init.js
lib/jquery.lazyload.js
common/lazyload.init.js
main.js
app/home.js
----------------
common/test.js
app/home.js
grunt 编译打包 requirejs JavaScript
Michial
9 years, 10 months ago
Answers
自己找到问题了,原来require.config要全局使用的话必须单独在页面上引用,
写了一个完整的实例有兴趣可以下载来看
https://github.com/93html/requirejs-example
starway
answered 9 years, 10 months ago