【问题标题】:Typescript without module loader?没有模块加载器的打字稿?
【发布时间】:2016-10-17 10:51:25
【问题描述】:

我被一个使用 aspx 页面的旧软件卡住了。 我有一些控件 (ascx),它们几乎可以作为小型单页应用程序工作(例如,可以让您注册到时事通讯的控件,或者可以让用户自定义新闻提要的控件)。 (我知道……它不是真正的 SPA……)

我开始在这个小型微型项目中使用 VUE.js。我设法使这一切都使用纯 JavaScript。

现在我想使用 typescript 而不是 JavaScript。

我遇到的问题:当我创建我的打字稿并引用一些像 VUE 或我自己的模块时,它总是在生成的 js 文件中写入一些“require”命令(转译为 ES5)或一些 Import 命令(如果转译为 ES6)。

据我所知,这些命令应该由服务器上的某些模块加载器使用。但是我没有 Node.Js 服务器,也没有 Javascript 构建基础设施。有没有办法告诉打字稿只是忽略这些命令?然后,我将使用 ascx-control 中的模块手动引用所需的 JS 生成的文件。

【问题讨论】:

  • 浏览?....

标签: typescript


【解决方案1】:

在您的 tsconfig.json 中,module 属性应为 none

{
    "compilerOptions": {
        "module": "none"
    }
}

现在没有更多的amdsystem 代码。现在你不能再使用importexport 语句了。

没有这个,TypeScript 不知道你的脚本的顺序,你可能会出现 Js 未定义的错误。

要解决此问题,只需添加 triple slash directive 而不是 import 语句

现在 TypeScript 以正确的顺序编译所有脚本。
也使用 outFile 而不是 out 因为已弃用。

【讨论】:

  • 在我的用例中,当使用'module': 'none' 时,我得到src/errors.ts:25:14 - error TS1148: Cannot use imports, exports, or module augmentations when '--module' is 'none'. 25 export class AttributeError extends Error {。我该如何解决?
  • 我上面提到你不能使用没有模块的导入/导出
  • @Jus 我上面的新答案可能会对你有所帮助
  • "module": "none""outFile": "something.js" 不会产生任何输出。知道为什么吗?
  • 您还有其他编译错误吗?它可能被配置为在出错的情况下不输出。
【解决方案2】:

当然可以。您只需配置 tsc 即可在没有模块加载器语句的情况下输出代码。

例如,将所有代码放到一个大文件中。

{
    "compilerOptions": {
        "target": "es5",
        "outFile": "www/js/bundle.js",
        "sourceMap": true,
        "declaration": true,
        "removeComments": true,
        "sourceRoot": ""
    }
}

这可能会限制您使用 ES6 导入语句。您可能必须改用 typescript 定义的 namespaces

【讨论】:

  • 谢谢。我试试看
  • 这行不通,因为out(不推荐使用outFile)不尊重任何脚本顺序,在Js中会出现很多错误
  • 错误 TS6131:无法使用选项 'outFile' 编译模块,除非 '--module' 标志是 'amd' 或 'system'
【解决方案3】:

我也遇到过类似的情况,我想在旧的 aspx 系统中使用 ts -> js 转译,然后是 system.web.optimization 捆绑。

我的具体问题与this SO question 有关,即以键入方式使用moment.js,同时避免像那样生成输出

Object.defineProperty(exports, "__esModule", {
    value: !0
});
var moment = require("moment");

这会导致像

这样的 js 错误
ReferenceError: exports is not defined

我发现添加了

"module" : none 

到 tsconfig.json 以及 moment.d.ts 文件的副本及其行

 export = moment;

已删除或注释掉。

 {
      "compileOnSave": true,
      "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es5",
        "outDir": "scriptoutput", //,
        "allowSyntheticDefaultImports": true,
        "module": "none"
        //"typeRoots": [ "node_modules/@types/", "node_modules/moment/" ]
      },
      "exclude": [
        "node_modules",
        "wwwroot",
        "scriptoutput"
      ],
      "include": [
        "script/custom-typings/moment.d.ts",
        "**/*"
      ]
    }

辛苦了,现在我的 ts 工作正常,无需加载任何模块,而且打字有助于使 typescript 棒极了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2023-03-29
    • 2016-04-11
    • 1970-01-01
    • 2021-11-24
    • 2021-05-21
    相关资源
    最近更新 更多