hi! Everybody is good! I am a medical examiner, a treatment department front-end code ape 🐒, dialogue with the code, listen to the voice of their heart, looking forward to everyone’s praise 👍 and attention ➕.

TS modular

1. How to write modularity in TS

You are advised to use ES6 modular standards to import and export modules in TS

Create a new module.ts file and export the variable name and function numRes

// Export the variable name and function numRes
export const name = "Forensic";

export function numRes(num1:number,num2:number) {
    return num1 + num2;
}
Copy the code

Create the index.ts file to import name and numRes

import { name, numRes } from "./myModule";

console.log(name);// Output "forensics"
console.log(numRes(1.2));/ / print 3
Copy the code

It is easy to use modularity in TS, and we do not need to write our own import. We can use TS smart tips, as follows:

If you want to make use of the TS intelligent prompt, you need to use the normal export mode instead of the default export mode, which does not have the intelligent prompt

// Normal exports have intelligent prompts
export const name = "Forensic";

export function numRes(num1:number,num2:number) {
    return num1 + num2;
}

// There is no intelligent prompt for the default export
export default {
    name: "Forensic".numRes:function (num1:number,num2:number) {
        returnnum1 + num2; }}Copy the code

Import {name, numRes} from “./ mymodule. ts”; import {name, numRes} from “.

The import module file will be compiled. If there is a TS suffix, the js file cannot be found in the compiled js file. Therefore, an error will be reported

2. Modularity of compilation results

When modularity is used in TS, sometimes ES6 modularity is used, sometimes CommonJS modularity is used, so it is also necessary to know which modularity standard is used in compiled JS.

The module property in tsconfig.json is used to specify which modularity standard the compiled JS file uses

{
  "compilerOptions": {// Configure compilation options
    "target": "es2016".// Which ES standard is used when compiling
    "module": "es6".Commjs is a standard in node environments, and es6 can also be used
    "lib": ["ES2016"].// The dom environment is available by default, but it is not available now
    "outDir": "./dist".// Which directory to put the compiled results in
    "strictNullChecks": true.// indicates stricter null-type checking}},Copy the code
  • Compare pre – and post-compile using the ES6 standard

    Es6 modular export:

    Since TS itself uses ES6 standards, and the compilation results are configured to ES6 standards, there is no code difference between the two. The compilation results only remove type constraints.

    Es6 Modular Import:

    From the point of view of the code, importing using the ES6 module is exactly the same without any difference

    👉 Tips:

    If you do not want the comment to be compiled into the result, you can configure “removeComments”: true in tsconfig.json,// to remove the comment.

    {
      "compilerOptions": {// Configure compilation options
        "target": "es2016".// Which ES standard is used when compiling
        "module": "es6".Commjs is a standard in node environments, and es6 can also be used
        "lib": ["ES2016"].// The dom environment is available by default, but it is not available now
        "outDir": "./dist".// Which directory to put the compiled results in
        "strictNullChecks": true.// indicates stricter null-type checking
        "removeComments": true.// Removes the comment}},Copy the code
  • Use CommonJS to compare before and after compilation

    CommonJS modular export:

    When we use commonJs modular export, we will find that the result after compilation is very different from before compilation. In the JS file, we will find that the first line is use strict mode, actually use strict does not need to appear in the compilation result, because we write TS code is strict enough. So we can configure:

    {
      "compilerOptions": {// Configure compilation options
        "target": "es2016".// Which ES standard is used when compiling
        "module": "CommonJS".Commjs is a standard in node environments, and es6 can also be used
        "lib": ["ES2016"].// The dom environment is available by default, but it is not available now
        "outDir": "./dist".// Which directory to put the compiled results in
        "strictNullChecks": true.// indicates stricter null-type checking
        "removeComments": true.// Removes the comment
        "noImplicitUseStrict": true.// Indicates that the compilation result does not contain use strict}},Copy the code

    Object.defineproperty (exports, “__esModule”, {value: true}); This line of code is the equivalent of exports._esModule = true; As for what it does, I won’t talk about it here, but I’ll talk about it later.

    CommonJS modular import:

    There is no import in commonJs. from.. In the compiled result, it will automatically declare a variable, myModule_1, which is the filename + “_” + number. If there are multiple imports, the number will increase successively.

    Many times during the development process, you don’t need to care what the result of the import/export compilation is, but it is helpful to know the result of the compilation to deal with the details

    Conclusion:

    • If the compiled result is modular standard ES6: no difference
    • If the resulting modularity standard is commonJS, the exported declaration will become an export property and the default export will become the default property of exports

    If we want to use fs in Node, we will get an error. For example:

3. Resolve the default import error

This section investigates the error generated when using the default export in TS. If you want to know the cause, you can see the result after compiling

Fs/module.exports = {} / module.exports = {} / module.exports = {}

Can produce such a problem, because some of the modules are not written by our own, we can write their own unified use ES6 module directly, will not have what problem, but before some module USES module. Exports is derived by means of = {}, it’s very embarrassed, can only look for other solution, the above is one of the way, This is not a good idea, because there is not just one function in the FS object. There are many functions in the fs object, and we can’t write all of them, which would be too cumbersome, but we can import all of them and give them individual names:

But for the obsessive-compulsive, I don’t want to use this approach, so there is one last option, which is to configure “esModuleInterop”:true in tsconfig.json, which means to start the ES modular interactive non-ES module export

{
  "compilerOptions": {// Configure compilation options
    "target": "es2016".// Which ES standard is used when compiling
    "module": "CommonJS".Commjs is a standard in node environments, and es6 can also be used
    "lib": ["ES2016"].// The dom environment is available by default, but it is not available now
    "outDir": "./dist".// Which directory to put the compiled results in
    "strictNullChecks": true.// indicates stricter null-type checking
    "removeComments": true.// Removes the comment
    "noImplicitUseStrict": true.// Indicates that the compilation result does not contain use strict
    "esModuleInterop":true.// Start es modular interactive non-ES module export}},Copy the code

After configuration, the code will not report errors

4. How to use it in TSCommonJsImport and export

  • Export = XXX;

    // For example
    export = {
        name:"Forensic".sayHello(a:string,b:string){
            returna + b; }}Copy the code
  • Import: XXX = require(” XXX “);

    // For example
    import module = require("myModule");
    Copy the code

The last

Thank you very much for reading the last 😘. If you think this article is helpful to you, you may wish to pay attention to ➕+ like 👍+ collect 📌+ comment ➕. Your support is the biggest motivation for me to update.