首页 > 解决方案 > (Javascript)如何将文件/一堆代码转换为变量?

问题描述

假设我有一个 helloworld.js 和一个 test.js 文件。在 test.js 文件中,我想创建一个 const:

const helloworldFile = *contents of helloworld.js* file.

我该怎么做?

例如 helloworld.js 的内容是:

console.log(1+1)

怎么做

const helloworldFile = console.log(1+1)

标签: javascript

解决方案


如果您想在其他地方使用一个文件中的函数,您可以从该文件中导出它,如下所示:

export const someFunction = () => console.log(1 + 1)

并将其导入到顶部的另一个文件中,如下所示:

import { someFunction } from './helloworld.js' // or whatever the relative path to the file is

然后,您可以在该文件中的任何位置使用该函数。这就是你想要做的吗?


推荐阅读