2015-01-20 60 views
1

我使用生成一个静态网站写grunt我想从我的玉模板调用moment.js。如何在Jade模板中包含客户端脚本?

我不知道我应该如何加载时刻库。

official documentation说:

require.config({ 
    paths: { 
     "moment": "path/to/moment", 
    } 
}); 
define(["moment"], function (moment) { 
    moment().format(); 
}); 

但我不知道异步加载如何与玉。

所以我写了这个代码无法编译:

doctype html 
html(lang="en") 
    head 
    script(src='scripts/require.js') 
    script. 
     require.config({ 
      paths: { 
       "moment": "scripts/moment.js", 
      } 
     }); 
    body 
    p #{moment(Date.now()).format('MM/DD/YYYY')} 

,出现以下错误:

>> TypeError: src/test.jade:7 
>>  5|  script. 
>>  6|   require.config({ 
>> > 7|    paths: { 
>>  8|     "moment": "scripts/moment.js", 
>>  9|    } 
>>  10|   }); 
>> 
>> undefined is not a function 

我怎么加载我的时刻对象,因此它可以用在翡翠(模板和mixin)?

Note if I replace the line p #{moment(Date.now()).format('MM/DD/YYYY')} with p #{Date.now()} it compiles.

+0

我不知道,但错过缩进是最大的嫌疑人。 Jade是模板引擎。所以你必须按照Jade的方式遵循缩进和其他。 – lv0gun9 2015-01-21 00:03:37

+0

我尝试了不同的缩进。但无济于事(我更新了我的问题)。 此外,翡翠不需要缩进的JavaScript,对吧? – 2015-01-21 00:07:15

+0

我对此有疑问。你的jade文件包含requirejs,它叫做momoentjs。顺便说一句,你最后的代码想要在模板上写入函数结果给html - > html时刻正确吗? – lv0gun9 2015-01-21 00:36:26

回答

1

诀窍就是让你的JavaScript时可用咕噜叫玉编译器生成最终的HTML文件

Note the ouput of the javascript will be statically copied into the html file. The javascript library is a compile time (devDependency) only dependency.

简单的测试文件

doctype html 
html(lang="en") 
    head 
    body 
    p #{moment(Date.now()).format('MM/DD/YYYY')} 
    p Hello guys !! 

咕噜文件

module.exports = function(grunt){ 
    ... 
    grunt.initConfig({ 
     pkg: grunt.file.readJSON('package.json'), 
     ... 
     moment = require ('moment') ; 
     grunt.registerTask(... 
     ... 

包文件

{ 
    "name": "site", 
    ... 
    "devDependencies": { 
    ... 
    "moment": "*" 
    }, 
    "dependencies": { 
    ... 
    } 
} 

Thanks to @ForbesLindesay for his help