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

How to include client-side script in Jade template?

本文关键字:包含 客户端 脚本 Jade      更新时间:2023-09-26

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

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

官方文件说:

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

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

请注意,如果我将行 p #{moment(Date.now()).format('

MM/DD/YYYY')} 替换为 p #{Date.now()},它就会编译。

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

请注意,javascript 的输出将被静态复制到 html 文件中。javascript库是一个编译时(devDependency)唯一的依赖项。

简单的测试文件

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": {
    ...
  }
}

感谢@ForbesLindesay的帮助