最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use Typescript to output plain JS, not a module? - Stack Overflow

programmeradmin3浏览0评论

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 pile 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 oute. 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.

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 pile 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 oute. 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.

Share Improve this question edited Mar 20, 2019 at 21:40 Josh M. asked Mar 20, 2019 at 20:27 Josh M.Josh M. 27.8k27 gold badges131 silver badges222 bronze badges 2
  • 2 You can't use import to do that. However, you can use a namespace – Get Off My Lawn Commented Mar 20, 2019 at 20:28
  • Possible duplicate of Typescript without module loader? – artem Commented Mar 20, 2019 at 20:37
Add a ment  | 

1 Answer 1

Reset to default 7

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

{
  "pilerOptions": {
    "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

{
  "pilerOptions": {
    "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./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./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.

{
  "pilerOptions": {
    "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();
}
发布评论

评论列表(0)

  1. 暂无评论