Spm2 最新的版本和Spm1.x有一点小小的区别。。所以照着Seajs+Spm的Hellospm的步鄹做发现没有达到想要的结果。于是经过摸索最终完成了这个hellospm项目:
把自己做的过程简单记录下,方便参考:
1.下载安装spm2,安装git,使用spm init建立开发目录
2.使用spm install seajs /spm install jquery ,
spm 安装后的jquery没有模块化,自己在代码中加上
define(function () {
//jquery source code
return $.noConfit(true);
}
完成模块化。
3.开始业务模块的开发在src目录中放入项目的要使用的源代码:
//util.js
define(function(require, exports) {
exports.random = function(min, max){
return min + Math.round(Math.random() * (max - min))
}
})
//hello.js
define(function(require, exports, module) {
var $ = require('$')
var random = require('./util').random
var handleText= require('./handle-text')
function Hello(){
this.render()
this.bindAction()
console.log('new Hello() called.')
}
Hello.prototype.render = function(){
this.el = $('<div style="position:fixed;'
+ 'left:' + random(0,70) + '%;'
+ 'top:' + random(10,80)+ '%;">'
+ handleText('Hello SPM !')
+ '</div>').appendTo('body')
}
Hello.prototype.bindAction = function(){
var el = this.el
setTimeout(function(){ el.fadeOut() }, random(500,5000))
}
module.exports = Hello
})
//hello-text.js
define(function(require, exports, module) {
var $ = require('$')
var random = require('./util').random
function handleText(text){
var min = random(30,70)
var max = random(50,120)
var rt = ''
for(var i = 0, len = text.length; i < len; i++){
rt += '<span style="font-size:' + random(min, max) + 'px;">' + text[i] + '</span>'
}
return rt
}
module.exports = handleText
})
4.修改项目根目录下的package.json文件
{
"family": "hello",//spm-init自己命名
"name": "hello",
"version": "1.0.0",
"description": "hello",//spm-init自己命名
"spm": {
"output": [ //项目输出所需要的js
"hello.js",
"util.js",
"hello-text.js"
],
"alias": { //项目依赖文件
"$":"jquery/jquery/1.9.1/jquery"
}
}
}
5.在项目根目录下运行命令: spm install spm build
6.可以看到在醒目目录下生产dist的目录文件,将dist下文件copy到 sea-modules/{{family}}/{{name}}/{{version}}下
7.大功告成现在可以在根目录下建立 index.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>hello-spm</title>
</head>
<body>
<div style="text-align:center;font-size:48px;color:#999;"> Press the space key !</div>
<script src="./sea-modules/seajs/seajs/2.1.1/sea.js"></script>
<script>
seajs.config({
alias:{
'$':'jquery/jquery/1.9.1/jquery'
}
})
seajs.use(['$','./sea-modules/hello/hello/1.0.0/hello.js'],function($, Hello){
$(document).keypress(function(ev){
if(ev.which == 32){
new Hello()
}
})
})
</script>
</body>
</html>
通过chrome浏览器查看页面的效果。。。狂按空格键。。。页面随机的出现hellospm字样。。。通过调试工具也可以看到
隐藏了。。。util.js和hello-text.js的文件加载。。。 水平有限。。大神留情。。