简体   繁体   中英

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

I'm trying to make a userscript in TypeScript using Webpack and Hogan.js pre-compiled templates.

For it to work, I need to import a compiled file, carousel_inner.js . This file is auto-generated, so no modifications to it are allowed.

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: {  }});

I'm trying different strategies to import the templates variable and export it for usage elsewhere, but I always end up with a "templates is not defined" error.

Here's a failed attempt.

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

The project is here .

Make a declaration type file.

carousel_inner.d.ts (.d.ts IS REQUIRED)

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

  export default types;
}

It will give types to a file that is being imported. I use the following for importing sql files occasionally.

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

Just use the type you want instead of unknown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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