【问题标题】:How to configure a start up javascript-only project with multiple files in VSCode如何在 VSCode 中配置具有多个文件的仅 javascript 启动项目
【发布时间】:2021-12-31 00:54:09
【问题描述】:

我正在使用 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,但没有成功。

我没有成功地尝试找到修改文件的方法,例如:

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

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

我在 StackOverflow 中找不到答案。

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

非常感谢,托马斯。

【问题讨论】:

    标签: javascript visual-studio-code configuration


    【解决方案1】:

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

    【讨论】:

    • 这非常有帮助!我错过了 test-02.js 中的导出语句。感谢 Nikola 如此迅速地回复!关于 HTML sn-p,如果我没有 HTML 文件怎么办?我可以忽略第一个代码 sn-p 吗?现在我只想要我们的 js 文件而不是 HTML,如果可能的话。
    • 是的,有可能。您可以使用节点运行它(必须安装nodejs.org/en)首先,在终端中运行“npm init -y”。接下来,将其添加到您的 package.json 文件中:“type”:“module”。最后,在终端运行“node test-01.js”,会输出正确的结果。
    猜你喜欢
    • 2018-08-01
    • 2022-12-25
    • 2013-07-06
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2021-06-22
    相关资源
    最近更新 更多