简体   繁体   English

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

[英]How to include client-side script in Jade template?

I'm using jade to generate a static website written grunt and I want to call moment.js from my jade template. 我正在使用jade生成一个静态的书面grunt网站,我想从我的jade模板中调用moment.js。

I don't know how I am supposed to load the moment library. 我不知道应该如何加载力矩库。

The official documentation says: 官方文件说:

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

But I'm not sure how the async loading works with jade. 但是我不确定异步加载如何与玉一起使用。

So I wrote this code that doesn't compile: 因此,我编写了以下无法编译的代码:

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')}

with the following error: 出现以下错误:

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

How am I supposed to load my moment object so it can be used in Jade (templates and mixins)? 我应该如何加载我的力矩对象以便可以在Jade(模板和mixins)中使用?

Note if I replace the line p #{moment(Date.now()).format('MM/DD/YYYY')} with p #{Date.now()} it compiles. 注意,如果我将p#{moment(Date.now())。format('MM / DD / YYYY')}替换为p#{Date.now()},则会进行编译。

The trick is to make your javascript available when grunt calls the jade compiler to generate the final html file 诀窍是当grunt调用jade编译器生成最终的html文件时,使您的JavaScript可用

Note the ouput of the javascript will be statically copied into the html file. 请注意 ,javascript的输出将被静态复制到html文件中。 The javascript library is a compile time (devDependency) only dependency. javascript库仅是编译时(devDependency)依赖项。

Simple test file 简单的测试文件

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

Grunt file 咕file声文件

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

Package file 打包文件

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

Thanks to @ForbesLindesay for his help 感谢@ForbesLindesay的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM