• [Typescript] CommonJS Interop


    From source: https://www.typescript-training.com/course/intermediate-v1/03-modules/

    Things can sometimes get a bit tricky when consuming CommonJS modules that do things that are incompatible with the way ES Modules typically work.

    Most of the time, you can just convert something like

    const fs = require("fs")

    into

    // namespace import
    import * as fs from "fs"

    but occasionally, you’ll run into a rare situation where the CJS module you’re importing from, exports a single thing that’s incompatible with this namespace import technique.

    Here’s a small example of where the namespace import fails:

    While this error message is accurate, you may NOT want to follow the advice it provides in all situations.

    If you need to enable the esModuleInterop and allowSyntheticDefaultImports compiler flags in order to allow your types to compile, anyone who depends on your types will also have no choice but to enable them.

    Thankfully we have another option here — the use of an older module loading API that imports the code properly, and matches up the type information as well

    ////////////////////////////////////////////////////////
    // @filename: fruits.ts
    function createBanana() {
      return { name: "banana", color: "yellow", mass: 183 }
    }
     
    // equivalent to CJS `module.exports = createBanana`
    export = createBanana
    ////////////////////////////////////////////////////////
    // @filename: smoothie.ts
     
    import createBanana = require("./fruits")
    const banana = createBanana()
    import createBanana = require("./fruits")

    we have solved this by avoiding the use of an ECMAScript import/export. After all, the code we’re referring to here is not following the ES module spec to begin with

    The compiled output of this file will still be what we’re looking for in the CJS world

    "use strict";
    function createBanana() {
        return { name: "banana", color: "yellow", mass: 183 };
    }
    module.exports = createBanana;
    ////////////////////////////////////////////////////////
     
    
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var createBanana = require("./fruits");
    var banana = createBanana();
  • 相关阅读:
    hibernate入门
    struts文件上传
    Struts的增删改查
    struts入门
    Maven配置以及环境搭配
    layui增删改查
    easyui三
    A
    C. Permutation Cycle
    E
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16570800.html
Copyright © 2020-2023  润新知