繁体   English   中英

如何从 JavaScript 文件中导入变量并在 TypeScript 中使用它?

[英]How to import a variable from a JavaScript file and use it in TypeScript?

我正在尝试使用 Webpack 和 Hogan.js 预编译模板在 TypeScript 中制作用户脚本。

为了让它工作,我需要导入一个编译文件carousel_inner.js 此文件是自动生成的,因此不允许对其进行修改。

if (!!!templates) var templates = {};
templates["carousel_inner"] = new Hogan.Template({code: function (c,p,i) { var t=this;t.b(i=i||"");t.b("<a class=\"carousel-");t.b(t.v(t.f("class",c,p,0)));t.b("\" href=\"\" style=\"background-image: url(");t.b(t.v(t.f("background-image",c,p,0)));t.b(")\">\r");t.b("\n" + i);t.b("  <div>\r");t.b("\n" + i);t.b("    <h4>");t.b(t.v(t.f("h4",c,p,0)));t.b("</h4>\r");t.b("\n" + i);t.b("    <h5>");t.b(t.v(t.f("h5",c,p,0)));t.b("</h5>\r");t.b("\n" + i);t.b("    <p>");t.b(t.v(t.f("p",c,p,0)));t.b("</p>\r");t.b("\n" + i);t.b("  </div>\r");t.b("\n" + i);t.b("</a>");return t.fl(); },partials: {}, subs: {  }});

我正在尝试不同的策略来导入templates变量并将其导出以供其他地方使用,但我总是以“未定义模板”错误告终。

这是一次失败的尝试。

// index.ts
import "./js/carousel_inner";
export default templates;
// main.ts
import templates from "./templates";
console.log(`templates: ${templates}`);

项目在这里

制作声明类型文件。

carousel_inner.d.ts (.d.ts 是必需的)

declare module "carousel_inner.js" {
  interface types {
    [index:string]:unknown;
  } 
  /* OR */
  type types = unknown;
  /* OR */
  const types:unknown; 

  export default types;
}

它将为正在导入的文件提供类型。 我偶尔使用以下导入 sql 文件。

declare module "*.sql" {
  const content: string;
  export default content;
}

只需使用您想要的类型而不是未知类型。

暂无
暂无

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

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