Use Typescript to output plain JS, not a module?

问题: For example ... index.ts import { x } from "./other-funcs"; function y() { alert("test"); } x(y); other-funcs.ts import { z } from "some-module"; export fun...

问题:

For example ...

index.ts

import { x } from "./other-funcs";

function y() {
    alert("test");
}

x(y);

other-funcs.ts

import { z } from "some-module";

export function x(callback: () => void): void {
    z();
    callback();
}

(Note that "other-funcs.ts" uses an import statement to import a function from some other module.)

I'd like to compile index.ts and have it result in a JS file which can be directly included in an HTML file, e.g. <script src="index.js"></script>, and have it immediately execute in the browser (show the alert).

sample output

function x(callback) {
    callback();
}

function y() {
    alert("test");
}

x(y);

I can't seem to get the proper TS config to get this outcome. Please advise.

Note: This is not the same as this question because I need to use import, etc. I just want the result to be simple JS output without a module loader.


回答1:

Vanilla JavaScript

Whenever you use import it will always build out to a module. You can however use namespaces alongside "module": "system", this can then be output to a single file (or multiple files).

so, for a very basic project you would have the following:

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "system",
    "outFile": "./lib.js"
  },
  "include": [
    "./**/*.ts"
  ]
}

Next you would then create your files to look like this:

index.ts

namespace MyNamespace {
  // This is a private method that cannot be accessed in other files
  // the reason for that is because it isn't exported.
  function y() {
    alert("test");
  }

  x(y)
}

functions.ts

namespace MyNamespace {
  // This method can be referenced in other files because it is exported.
  export function x(callback: () => void): void {
    callback();
  }
}

The generated browser code

var MyNamespace;
(function(MyNamespace) {
  function x(callback) {
    callback();
  }
  MyNamespace.x = x;
})(MyNamespace || (MyNamespace = {}));
var MyNamespace;
(function(MyNamespace) {
  function y() {
    alert("test");
  }
  MyNamespace.x(y);
})(MyNamespace || (MyNamespace = {}));

You can then use these methods/functions outside of the namespace by simply by calling them via the namespace:

MyNamespace.y()
MyNamespace.x(MyNamespace.y)
// etc.

Using requirejs

To use import within your project, you will need a 3rd party library requirejs. This will allow you to use modules within the browser.

So, to do this, we first need to have the proper config file which looks similar to above the only difference is "module": "amd".

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "amd",
    "outFile": "./lib.js"
  },
  "include": [
    "./**/*.ts"
  ]
}

Next we need to create the proper typescript main file:

index.ts

requirejs(['functions'], function (util: any) {
  function y() {
    alert("test");
  }

  util.x(y)
})

Since this is using a 3rd party library, it is initialized differently (using requirejs()). This tells requirejs that this is the entry point to the application thus this is only needed once.

functions.ts

export function x(callback: () => void): void {
  callback();
}

The generated browser code

define("functions", ["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function x(callback) {
        callback();
    }
    exports.x = x;
});
requirejs(['functions'], function (util) {
    function y() {
        alert("test");
    }
    util.x(y);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>

If your script is in an external file, you can use data-main on the script tag, requirejs will then load the file automatically.

<script data-main="./lib" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>

Experimental Modules

This feature is still experimental, and not supported in all browsers. All you need to do is use the type="module" attribute on your script tag:

<script type="module" src="./path/to/main.js"></script>

tsconfig.json

Note: that here we use both a different target and module, and also an outDir.
Note: es2016 is not a valid module type.

{
  "compilerOptions": {
    "target": "es2016",
    "module": "es2015",
    "outDir": "./lib"
  },
  "include": [
    "./**/*.ts"
  ]
}

index.ts

Note: import uses a .js extension otherwise the browser can't load it unless you have rewrite rules in place.

import { x } from './functions.js'
function y() {
  alert("test");
}

x(y)

functions.ts

export function x(callback: () => void): void {
  callback();
}

This will output nearly the same as the ts files (Stackoverflow doesn't support external js files unless they are hosted somewhere, so no snippet here):

// index.js
import { x } from './functions.js';
function y() {
    alert("test");
}
x(y);

// functions.js
export function x(callback) {
    callback();
}
  • 发表于 2019-03-22 00:40
  • 阅读 ( 254 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除