JavaScript >> Javascript 文檔 >  >> Tags >> TypeScript

使用 Typescript 創建 JavaScript 和 Typescript 包

Javascript 是最擁護環境的語言,包括 NPM 社區也有很多在 Javascript 環境下製作的包,作為 Typescript 程序員,我們必須意識到 Typescript 最終會被轉譯成 Javascript,因此,創建一個混合生態系統(Javascript 和 Typescript)變得非常重要,使用可執行 tsc 等工具 來自包typescript 成為執行轉譯過程的義務。

在本教程中,作者將展示如何創建一個混合包(接受兩種不同的模塊規範,也接受兩種具有相同環境的語言),您可以通過 Typescript 使用該包(線索:.d.ts required ) 或 Javascript。

創建項目文件夾

我們將為我們將首先構建的項目包創建一個文件夾,不要忘記創建一個具有正確格式的 package.json。

mkdir tsc-practice

cd tsc-practice
npm init -y # untuk memasang langsung semua default value pada package.json 

# atau
npm init # mengisinya satu persatu

免責聲明:以上文件夾名稱的使用不是opinionated ,可以自己確定。

安裝所需工具

我們將安裝 typescript 進行實際遊戲之前的轉譯過程,即在配置部分。

npm i -D typescript

創建配置文件

我們將創建一個接受 ESM 和 CJS 模塊環境的包。 tsc 具有使用不同配置文件的功能,這裡我們將為 ESM 和 CJS 創建配置文件。

在此之前,查看 tsc 提供的所有配置屬性 , 你可以使用 npx tsc --init ,根據這篇文章調整需求。

  • 為 CJS 創建配置文件

創建一個名為 tsconfig.cjs.json 的文件 在根目錄中,然後用下面的配置填充它。

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    /* Projects */
    /* Language and Environment */
    "target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
    /* Modules */
    "module": "commonjs" /* Specify what module code is generated. */ /* Specify the root folder within your source files. */,
    "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
    /* Emit */
    "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
    "declarationMap": true /* Create sourcemaps for d.ts files. */,
    "sourceMap": true /* Create source map files for emitted JavaScript files. */,
    "outDir": "dist/cjs" /* Specify an output folder for all emitted files. */,
    "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
    "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
    /* Type Checking */
    "strict": true /* Enable all strict type-checking options. */,
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  },
  // include used to fix: Cannot write file because it would overwrite input file when adding exclude.
  // "include": ["*.ts"],
  // "exclude": ["**/*.spec.ts"] // jika ingin menambahkan tests.
}

在這裡,我將分解使用的重要屬性,此外還有其他配置屬性以方便包開發。

這裡我們將使用 es6 作為最廣泛使用的 ecmascript 的規範,但如果您想轉換為更高的規範,例如 es2016 不要緊。在此處查找 EcmaScript 規範版本。

我們還將使用 "module": "commonjs" 告訴 tsc 使用 commonjs 模塊規範轉譯成 Javascript。

outDir 來確定 transpile 的位置。

  • 為 ESM 創建配置文件

創建一個名為 tsconfig.esm.json 的文件 在根目錄中,然後用下面的配置填充它。

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    /* Projects */
    /* Language and Environment */
    "target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
    /* Modules */
    "module": "ES6" /* Specify what module code is generated. */ /* Specify the root folder within your source files. */,
    "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
    /* Emit */
    "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
    "declarationMap": true /* Create sourcemaps for d.ts files. */,
    "sourceMap": true /* Create source map files for emitted JavaScript files. */,
    "outDir": "dist/mjs" /* Specify an output folder for all emitted files. */,
    "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
    "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
    /* Type Checking */
    "strict": true /* Enable all strict type-checking options. */,
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  },
  // include used to fix: Cannot write file because it would overwrite input file when adding exclude.
  // "include": ["*.ts"],
  // "exclude": ["**/*.spec.ts"] // jika ingin menambahkan tests.
}

創建包文件

創建文件 index.ts 在根目錄中然後輸入下面的示例腳本

export function greet(greeting: string): string {
  return greeting;
}

將腳本添加到 package.json

我們將添加一個名為 build 的新屬性 在 scripts 屬性屬性上 在文件 package.json 使用帶有 npm run build 的 tsc 運行轉譯過程 .

"build": "tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json",

轉譯

在正確執行所有步驟並且沒有錯誤之後,我們將執行轉譯過程。

npm run build

添加新屬性以支持 ESM 和 CJS 模塊規範

package.json 文件中的 json 對像中添加以下屬性 支持混合模塊規格

  "main": "dist/cjs/index.js",
  "module": "dist/mjs/index.js",
  "exports": {
    ".": {
      "import": "./dist/mjs/index.js",
      "require": "./dist/cjs/index.js"
    }
  },

main 用於返回調用require("foo")時導出的默認對象 .

module 是一個財產提案,但事實上 用於檢測ESM。

exports 用於指定使用import時使用哪個模塊 或 require .

npm 發布

最後一步是將你的包發佈到 NPM。

封面圖通過文章https://dev.to/wpreble1/introduction-to-typescript-32k獲得


Tutorial JavaScript 教程
  1. javascript構造函數重置:它是什麼?

  2. 20 個基本的 React 問題可以幫助你學習

  3. 如何觸手可及獲得數百萬個機器學習預測

  4. JavaScript 中的數據結構:數組

  5. 將普通函數重寫為箭頭函數

  6. 每個開發人員都喜歡的 10 大 JavaScript 模式

  7. 何時不使用 package-lock.json

  1. 找不到 Typescript 編譯器:命令 tsc 無效

  2. 我的 webpack 視頻課程的兩個新部分

  3. 帶有 Web 組件的更整潔的圖標

  4. Blazor 自動完成標記

  5. 5 個 Angular JS 種子和引導應用程序

  6. 如何修改 JavaScript 數組中的現有對象

  7. 理解 JavaScript 中的 Promise

  1. 使用 Colly 在 Go 中構建網絡爬蟲

  2. 在 NodeJS 中創建服務器 - 第 1 部分

  3. RxJS - 大理石圖

  4. remix.run + cloudflare 工人 + supabase + 順風