初學者指南:創建和使用 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 開發人員文檔。