簡體   English   中英

在另一個文件 javascript 中從 function 導入 const

[英]import const from function in another file javascript

我如何從 function 在另一個導出默認文件的文件中導入 const。

這是address.js(我想得到的const在哪里):

export default function addressUrl () {
  const email = Math.random().toString(25).substring(5) + '@xyz.com';
  return `grabiv/${md5(email)}`;
}

output.js(我想從address.js中使用這個常量)

import {email} from '../address;

export function gravatarImage (window) {
    document.getElementById("mail").innerText = email
}

也許是解決此故障的其他方法。 當我想在 const 之前寫“export”時,我得到了錯誤。

使用 function 更改您的第一個文件,以便您可以在模塊級別定義變量並將其導出:

let email;

export default function addressUrl () {
  email = Math.random().toString(25).substring(5) + '@xyz.com';
  return `grabiv/${md5(email)}`;
}

export email;

Note that I'm assuming you want the value of email to be set by the function addressUrl (so that if you call the function multiple times, a new email will be randomly generated each time, rather than using one value the whole time),如評論中所述,在調用此 function 之前,該值將是undefined

您可能需要將其與 function 內部分開

從約翰的評論中編輯:因為它是生成隨機電子郵件的情況,所以將其function以返回random emails並使用export

//address.js
export const email =()=> Math.random().toString(25).substring(5) + '@xyz.com'
export default function addressUrl (emailValue) {
  return `grabiv/${md5(emailValue)}`;
}

接着

//output.js 
//edit from awarrier's comment
import addressUrl,{email} from '../address;
export function gravatarImage (window) {
    document.getElementById("mail").innerText = email()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM