JavaScript >> Javascript 文檔 >  >> JavaScript

初學者指南:創建和使用 JavaScript ES6 模塊

這個簡短的教程旨在幫助您開始創建和使用 JavaScript 模塊並提供一些簡單的示例。

什麼是 ES6?

JavaScript 的正式名稱實際上是 ECMAScript, 並且版本 6 引入了模塊功能來創建和使用模塊,因此您可能會看到 JavaScript 模塊被稱為 ES6 或 ES2015 模塊。

什麼是 JavaScript 模塊?

隨著您對 JavaScript 編程項目的冒險程度越來越高,並且您的代碼變得越來越複雜,它可能會開始變得越來越難以管理。

緩解這種情況的一種方法是將代碼拆分為多個文件——每個文件都專注於特定任務或與程序的某個方面相關。

這就是 JavaScript 模塊 功能實現 - 它允許您將代碼組織到單獨的文件中,並在需要時導入它們。

它還允許您使用其他人的模塊 已編寫並可供使用 - 真正節省時間!

創建模塊

我將保持這個例子簡單。讓我們創建一個包含兩個函數的模塊:

  • 一個名為 shortestWord 的函數 返回給定字符串中最短的單詞
  • 一個名為 longestWord 的函數 返回給定字符串中最長的單詞

這是本文的示例模塊,wordCalc.js

// Define the function called **shortestWord** which returns the shortest word from a given string
function shortestWord(words){
    let splitWords = words.split(' ');
    let sortArray = splitWords.sort(function(a, b) { return a.length - b.length; }); // Sort the array from shortest to longest
    return sortArray[0]; // Return the first element in the array, which will be the shortest
}

// Define the function called **longestWord** which returns the longest word from a given string
function longestWord(words){
    let splitWords = words.split(' '); // Split the words up into an array of words
    let sortArray = splitWords.sort(function(a, b) { return a.length - b.length; }); // Sort the array from shortest to longest
    return sortArray[sortArray.length-1]; // Return the last item in the array, which will be the longest
}

// Export the above functions for use in other scripts 
export { shortestWord, longestWord };

出口 聲明

在上面的代碼中,您會看到 export 使用中的聲明。這就是模塊工作的原因。您出口 模塊中的變量和函數以及導入 它們在其他需要的文件中。

使用模塊

現在你有了一個模塊;你可以使用它。變量和函數導出 可以從模塊中導入 到你的其他 JavaScript 文件中:

// Import the functions from the module created in wordCalc.js
import { shortestWord, longestWord } from './wordCalc.js';

// Call the shortestWord from the module to test it
console.log(shortestWord("terrible dog")); // Prints 'dog'

// Call the longestWord from the module to test it
console.log(longestWord("fancy cat")); // Prints 'fancy'

導入 聲明

模塊難題的最後一塊是導入 上面使用的語句。它已從 wordCalc.js 導入函數 之前創建的模塊文件。當然,您不必從模塊中導入所有內容——您可以省略不需要的變量或函數,以使內容易於閱讀。

模塊可以從其他模塊導入並存儲在子目錄中。這是保持項目井井有條的便捷方式。

範圍

變量是作用域 在 JavaScript 中。因此,除非導出,否則在一個模塊中聲明的變量在其外部不可用。這包括模塊中的全局範圍變量——除非顯式導出,否則它們將不可用於其他模塊或您的整個應用程序。

結論

當您準備好深入了解 JavaScript 模塊時,請查看 Mozilla 開發人員文檔。


Tutorial JavaScript 教程
  1. 反應和 Vue 談話

  2. 如何設置您的 Gridsome 應用程序以使用 TypeScript

  3. React 組件生命週期方法 - 它們是什麼?

  4. Node.js Express 教程一步一步構建一個 1 頁的網站

  5. CSS 技巧:在不使用 JS 的情況下調整元素大小

  6. 如何在我的 node.js 環境中存儲來自 MariaDB 的數據

  7. 5 個好奇的 JavaScript 博客

  1. 如何在 React 應用程序中集成 TomTom API

  2. 編寫出色的 Svelte 測試的技巧

  3. 重構編年史:傳播運算符、映射、歸約。

  4. 創建您自己的 React 驗證庫:開發者體驗(第 3 部分)

  5. 5 個 jQuery Touch Swipe 圖片庫插件

  6. 適用於 Node.js 的 Application Insights SDK 第 5 部分:開箱即用遙測 - 異常、性能和實時指標流

  7. 改造,改造!第三部分:如何從 Wordpress 切換到 Jekyll

  1. 使用 Ember JS 第 1 部分製作 Electron 應用程序:初始設置

  2. 使用 Express 重定向

  3. 這就是我構建 Babel 插件的方式

  4. 通過 SSH 隧道/端口轉發從防火牆後面連接到 MongoDB