如何在VSCode中配置具有多个文件的仅启动javascript的项目



我正在与FCC一起学习javascript课程,并使用VSCode作为我的代码编辑器。但到目前为止,我所有的js代码都包含在一个文件中。显然,对于任何有意义的js开发,我都需要创建一个作为单个单元工作的js文件集合。

为了开始探索这一点,我有一个非常简单的两个js文件设置,test-01.js和test-02.js,其中test-01.jss包含对test-02.jss中定义的函数的调用。我首先想在没有任何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,但没有成功。

我试图找到修改文件的方法,但没有成功,比如:

  • package.json
  • jsconfig.json
  • setting.json
  • launch.json

我曾尝试在github和其他地方寻找示例项目,但没有成功。

我在StackOverflow中查找答案失败。

一切都无济于事。这应该是一个很容易的问题,应该在vscode文档中进行描述,但我在那里找不到它。到目前为止,我已经尝试了很多事情,可能已经把我的开发环境搞砸了。我希望有人能帮助我,并为我指明解决这个问题的正确方向。

非常感谢,托马斯。

JavaScript模块是从一个.js文件导入方法并在另一个.jss文件中调用它们的方法。在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:中定义"Display"函数

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);

最新更新