我正在與 FCC 一起學習 javascript 課程,并使用 VSCode 作為我的代碼編輯器。但到目前為止,我所有的 js 代碼都包含在一個檔案中。顯然,對于任何有意義的 js 開發,我都需要創建一組作為單個單元作業的 js 檔案。
為了開始探索這個,我有兩個 js 檔案的非常簡單的設定,test-01.js 和 test-02.js,其中 test-01.js 包含對 test-02.js 中定義的函式的呼叫。我首先想在沒有任何 HTML 或 CSS 檔案的情況下執行此操作。盡管這也將是未來的要求。
第一個檔案 test-01.js:
//test-01.js
let returnStr = "";
console.log("This is the calling program");
// Now call the function in test-02.js
returnStr = Display(10);
考慮到未來專案的復雜性,第二個檔案 test-02.js 位于第一個檔案的子檔案夾中。.\folder-02\test-02.js:
//test-02.js
function Display(param = 0) {
console.log("This is the program called with parameter: ", param);
return "Back from Display";
};
我嘗試將函式 Display() 從 test-01.js 匯入到 test-02.js 中,但沒有成功。
我沒有成功嘗試找到修改檔案的方法,例如:
- 包.json
- jsconfig.json
- 設定.json
- 啟動檔案
我曾嘗試在 github 和其他地方尋找示例專案,但沒有成功。
我在 StackOverflow 中尋找答案沒有成功。
一切都無濟于事。這應該很簡單,應該在 vscode 檔案中描述過,但我在那里找不到。到目前為止,我已經嘗試了很多東西,我可能已經搞砸了我的開發環境。我希望有人可以幫助我并指出我解決這個問題的正確方向。
非常感謝,托馬斯。
uj5u.com熱心網友回復:
JavaScript 模塊是從一個 .js 檔案匯入方法并在另一個 .js 檔案中呼叫它們的方法。在 JavaScript 中匯入和使用模塊有很多不同的方法:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
以下是針對您的情況的示例:
首先,讓我們將主要的 JavaScript 檔案匯入到 html 檔案中:
<head>
<!-- type="module" is necessary -->
<script type='module' src="test-01.js" defer></script>
</head>
接下來,讓我們在folder-02/test-02.js 中定義“顯示”函式:
function Display(param = 0) {
console.log("This is the program called with parameter: ", param);
return "Back from Display";
};
export default Display //exporting it to be imported into another js file
最后,讓我們設定test-01.js來匯入和呼叫之前定義的函式:
import Display from './folder-02/test-02.js';
let returnStr = "";
console.log("This is the calling program");
// Now call the function in test-02.js
returnStr = Display(10);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362247.html
標籤:javascript 视觉工作室代码 配置
