SoFunction
Updated on 2025-03-10

The difference between Module usage and module path resolution rules in TypeScript

Module in TypeScript

This article mainly introduces the difference between module and non-modules in TS;.The function of the file; and the resolution rules of module paths;

The code file in TS that stipulates that the top-level import and export keywords exist are considered a module, and files without the top-level import and export are considered general scripts.

The difference between modules and scripts

There are differences in the following directions between modules and scripts non-modules. This is the difference between modules and scripts in JavaScript (the same is true for TypeScript).

  • Differences in scope

module has its own scope. Variables, functions, and classes defined in modules all exist in their own scope, and external modules and script codes are not visible.

non-modules run on global scope. Variables, functions, and classes defined at the top level all exist in the global scope. Both external modules and scripts are accessible.

  • Export and import

module Use the import export keyword to control the import snippets (variables, functions, classes, etc.) from other modules and the export snippets in the module respectively.

The functions and variables defined in non-modules are in the global scope, so no additional import and export operations are required and can be accessed directly globally.

  • Code Management

module is convenient for code division and organization, and can divide modules according to abstract levels or functions, which is convenient for code organization.

Script code is generally written in several unified files, and you need to pay attention to the access order of variables, and there is a risk of contaminating the global scope that needs to be avoided.

  • Dependency management

Module dependencies are used to display specified dependencies through import, allowing better control of dependencies and reducing the possibility of naming conflicts.

The dependencies of scripts are hidden (you need to read the code carefully and debug it layer by layer to analyze it clearly). The scripts are executed in the order of shelf. The order of loading between scripts is very important. [The order of scripts loading may change: errors such as function not found, variables not defined]

  • Loading timing

The module supports asynchronous loading, and the code is executed after loading is completed, which can reduce blockage in HTML document parsing.

Scripts are classic synchronous loading. If a synchronous script appears in HTML, you need to wait for the code to load and execute the HTML parsing before continuing to execute. Usually, except for some code that needs to be executed in advance (permission checking, user verification, etc.), the rest of the code is loaded at the end of the HTML document (it can be loaded explicitly asynchronously).

// 

export function foo(params) {
    //...
}

export class Bar {
    constructor() {
        //...
    }
}
// 

import { foo, Bar } from './';

export function run(){
    const ins = new Bar();

    // ...
    return foo(ins);
}

Module loading mechanism in TS

The relationship between modules is established by import and export. There are two ways to specify the path when the module is loaded, one is relative path and the other is non-relative path. The relative path calculates the index based on the current file location to find the file location. The non-relative position module import compiler will traverse to the previous directory from the directory containing the imported file, trying to match the corresponding file.

. Usage of files and related content

In TypeScript,.Files are usually used to define type declarations for JavaScript libraries or modules. They are files used to describe the type information of existing JavaScript code, mainly describing the structure of JavaScript modules (export class parameter types, function signature formats, etc.) to facilitate type checking and intelligent awareness reminders in ts code. When writing code with TypeScript, you can use a type declaration file to obtain type checking and intelligent awareness support for JavaScript libraries or modules. These declaration files usually.is an extension.

By introducing the appropriate type declaration file, you can help:

  • Type Check: The type declaration file allows the TypeScript compiler to verify that the code matches the type defined in the declaration file. This helps catch potential type errors during development and provides more powerful static type checking.
  • Intelligent Perception: The type declaration file provides the editor with type information about the library or module, thus providing intelligent sense functionality. This allows you to obtain functions such as automatic completion, parameter prompts and documentation when writing code to increase development efficiency.
  • Documentation: A type declaration file can also be used as a document for a library or module. By looking at the type declaration file, you can learn more about the library's available functions, classes, interfaces, and types, and so on, so that you can better understand and use them.

In case, define a worker to implement the processing of data in ThreeJS:

onmessage(params) {
  //
  const data: Block[] = [];
  ... A large number of calculations
  // Return after the thread calculation is completed  postMessage({ fragments: data  }, timestamp: );
}
declare module '*?worker' {
  const workerConstructor:{
    new (): Worker
  };
  export default workerConstructor
}
import './';
import Worker from './?worker'
function calculateAllBlocks(threadCount: number) {
  for (let i =0; i< threadCount; i++) {
    const worker = new Worker();
     = dataParse;
    // Incoming parameters start thread for calculation    ({..., timestamp: ()});
  }
}
function dataParse(workerEvent: MessageEvent) {
  // Processing thread returns data}

In this way, we can quickly define a thread processing module code without defining it as js and then passing it as a parameter to load and execute. The Worker type used in the module is also legal, because it was imported to interpret the type.

A suffix module is used to declare the wildcard character, that is, "*?worker". Only by adding a suffix that can pass the verification can the export module be correctly matched (note the import in it). The wildcard declared in TS will only use the corresponding type to interpret the target module if it is exported.

The above is the detailed content of the difference in Module usage and module path analysis rules in TypeScript. For more information about TypeScript Module module paths, please pay attention to my other related articles!