簡體   English   中英

模塊名稱字符串的 TypeScript 類型

[英]TypeScript type for module name string

背景: TypeScript 檢查您嘗試和導入的模塊,如果使用的字符串文字與實際模塊的名稱或受支持文件類型的路徑不匹配,則會在編譯時失敗。

例如import {Component} from 'react'import item from './item'編譯得很好,但是import {Component} from 'reactt'import item from './otem'將無法編譯假設有react安裝了模塊和項目中的item.ts文件,但沒有安裝reactt模塊,並且項目中沒有擴展名為 .ts、.js、 ./otem文件。

問題:我不確定如何創建一個函數,其中一個參數是必須對應於實際模塊或受支持文件的字符串文字。

function customImportEffect(moduleName: module_string_literal) {
    ...
}

module_string_literal應該是什么類型,以便在提供不正確的輸入(例如'reactt''./otem'作為參數時編譯時檢查失敗?

問的原因:我正在嘗試制作一個 webpack 文件轉換器(又名加載器),它在轉換 TypeScript 文件之前將代碼添加到它們的頂部,因此用戶可以擁有類型安全的熱模塊重新加載代碼。 例如,假設在轉換為 JS 之前,在每個 typescript 文件上方插入以下代碼:

class HotModule {
    public static accept(moduleName: module_string_literal, onModuleReplace: Function(updatedModule: typeof import(moduleName)):void) {
        if(module.hot) {
            module.accept(moduleName.toString(), function() {
                onUpdate(require(moduleName.toString()))
            }
        }
    }
}

然后熱模塊重新加載可能是類型安全的並且看起來更干凈。 假設 ./item.ts 文件的默認導出是一個具有名為message的成員的對象,可以這樣寫

HotModule.accept("./item", ({message: newMessage}) => {
    const oldMessage = message;
    messages[messages.indexOf(oldMessage)] = message = newMessage;
}

實現消息的熱重載,而不是

if(module.hot) {
    module.hot.accept("./item", function() {
        const oldMessage = message;
        messages[messages.indexOf(oldMessage)] = message = require("./item");
    }
}

我希望這可能是可能的,因為從 TypeScript v2.4 開始,就有了異步動態導入模塊的能力,並且檢查了提供的字符串文字的正確性,不正確的字符串文字會導致編譯時失敗。

目前我只是在我的tsconfig.json文件的compilerOptions對象中包含"types": ["webpack-env"] ,但我想要一個熱模塊 API,它可以更好地利用 TypeScript 的檢查工具集。

用內容在某處制作一個 module-type.d.ts

import json from "./package.json" // or whereever your package json is
export type ModuleName=keyof typeof json["dependencies"]

您需要在 tsconfig 中啟用 jsonmodule

"resolveJsonModule": true,

然后你將它導入任何你需要的地方

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM