如何在 Jade 模板中包含客户端脚本?

How to include client-side script in Jade template?

我正在使用 jade 生成一个写成 grunt 的静态网站,我想从我的 jade 调用 moment.js模板。

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

official documentation 说:

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

但我不确定异步加载如何与 jade 一起工作。

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

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

我应该如何加载我的 moment 对象以便它可以在 Jade 中使用(模板和混合)?

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

诀窍是在 grunt 调用 jade 编译器生成最终的 html 文件时让你的 javascript 可用

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 !!

Grunt 文件

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