简体   繁体   中英

Cannot find imported Module TypeScript

I am trying to setup new TypeScript HTML project in VS 2015. I have set the typescript build settings to commonJs , es5 and also had the tsconfig.json , which is

   {
 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "sourceMap": true
   }
}

Here is my main app.ts

  import t = require('./test');

class Greeter {
element: HTMLElement;
span: HTMLElement;
timerToken: number;
t: any;

constructor(element: HTMLElement) {
    this.element = element;
    this.element.innerHTML += "The time is: ";
    this.span = document.createElement('span');
    this.element.appendChild(this.span);
    this.span.innerText = new Date().toUTCString();
    this.t = new t.sample.test();
}

start() {
    this.timerToken = setInterval(() => this.span.innerHTML = new Date().toUTCString(), 500);
    this.t.hello();
}

stop() {
    clearTimeout(this.timerToken);
  }

 }

 window.onload = () => {
  var el = document.getElementById('content');
   var greeter = new Greeter(el);
   greeter.start();
};

Here is my imported module test.ts

   export module sample {
export class test {
    constructor() { }
    hello = () => {

        console.log("Test");
    }
  }
 }

Here is the html.

    <!DOCTYPE html>

    <html lang="en">
    <head>
     <meta charset="utf-8" />
      <title>TypeScript HTML App</title>
   <link rel="stylesheet" href="app.css" type="text/css" />
  <script src="test.js"></script>
  <script src="app.js"></script>


    </head>
   <body>
    <h1>TypeScript HTML App</h1>
   <div id="content"></div>
   </body>
   </html>

The project builds fine, but when i open that in browser chrome or IE, it throws error in console that it cannot find test and the file is never downloaded in to browser. Can any one suggest what I am missing here.

Here is my recommended fix...

Step One - compile for AMD (or UMD) instead of CommonJS:

"module": "amd",

Step Two - ditch the internal module here:

  export module sample {

Step Three - Add RequireJS (Available as a NuGet package)

Step Four - Use Require JS

<script src="require.js" data-main"app"></script>

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