简体   繁体   English

当我从 another.js 文件导入某些内容时,Function 无法正常工作

[英]Function not working when I import something from another .js file

I have a two.js files, one is the main one and the other is used to write and export the functions.我有两个.js 文件,一个是主要的,另一个是用来编写和导出函数的。 My problem is: when I import a function from funciones.js to index.js my main function stops working.我的问题是:当我将 function 从funciones.js导入到index.js时,我的主要 function 停止工作。

This is the code:这是代码:

Index.js:索引.js:

import { currentWeather } from './funciones.js';


function findWeather() { //this function stops working

        //Defining the APIs for both current weather and forecast
        let location1 = document.getElementById('Search').value;
        console.log(location1);
        //...

Funciones.js:函数.js:

export function currentWeather(wName) { //the function I am exporting
    switch (wName) { //Switch conditions to display the correct status and imges
        case "Thunderstorm":
        //...

I've got to the conclusion that I'm doing something wrong at exporting, because the main function ( findWeather ) only stops working by the time I import something.我得出的结论是我在导出时做错了,因为主要的 function ( findWeather )只有在我导入某些东西时才停止工作。 I've tried to write everything in the same file and it works, but the idea is to have separated files.我试图将所有内容都写在同一个文件中并且它可以工作,但我的想法是分开文件。

I've tried to export the function at the end of the file as well, and it still doesn't work.我也尝试在文件末尾导出 function ,但它仍然不起作用。

All files that are involved must have .mjs extension.涉及的所有文件都必须具有.mjs扩展名。

Be careful in choosing the name of the functions.选择函数的名称时要小心。 Both must have the same name.两者必须具有相同的名称。 For example functions.js.If you can, write the complete code to check it.例如functions.js。如果可以的话,写完整的代码来检查它。

I've figured it out.我已经想通了。

The solution I found is: export the main function ( findWeather() ) and then call it, or in another .js file, or in a <script> tag in the HTML.我找到的解决方案是:导出主要的 function ( findWeather() ) 然后调用它,或者在另一个.js文件中,或者在 HTML 中的<script>标记中。

So it would look like:所以它看起来像:

funciones.js: funciones.js:

export function currentWeather(wName) { //the function I am exporting
    switch (wName) { //Switch conditions to display the correct status and imges
        case "Thunderstorm":
        //...

index.js: index.js:

import { currentWeather } from './funciones.js';


 export function findWeather() {

        //Defining the APIs for both current weather and forecast
        let location1 = document.getElementById('Search').value;
        console.log(location1);
        //...

Index.html:索引.html:

<script type="module">
   import { findWeather } from './index.js';
   findWeather();
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM