在其他文件中使用变量和函数是 Node js
Using variables and functions in other fileis Node js
我有两个单独的文件,我想在另一个文件中使用第一个文件中的函数和变量。
我的意思是,这是我的第一个文件的内容:
const db = mongoose.connection;
在我的第二个文件中,我需要记录它:
console.log(db)
我使用了导出和导入,但没有用:
export const db = mongoose.connection;
import db from (./db.js)
console.log(db)
我收到这个错误:
语法错误:无法在模块外使用导入语句
您是否也创建了 HTML 文件?如果是这样,请尝试将第二个文件作为模块类型加载以修复错误。
将此放入您的 HTML 文件中:
<script type="module" src="secondScript.js"></script>
在节点 js(或现代其他 js 平台)中,您可以使用模块。
在节点 js 中。你有2个选择。
1: 通用 js (CJS) 模块:
in a way, nodeJS based on CJS. and CJS modules builtin available in node.
you can imort a CJS module with this code :
const module = required("module file widout .js");
以及创建模块(在您的模块文件中):
module.export = {your code};
2 个 ES6 模块:
es6 is a newer version of JS and that supports modules defaultly.
使用模块:
你的例子:)(有问题post):
from module import a;
console.log(a); //1
创建模块:
export a = 1
对 ES6 模块非常重要: 你应该使用 js 编译器,比如 babel 将 es6-21 编译为 es5 nodeJS 和浏览器(我不知道其他平台)不支持es6或以上的JS版本。
我有两个单独的文件,我想在另一个文件中使用第一个文件中的函数和变量。 我的意思是,这是我的第一个文件的内容:
const db = mongoose.connection;
在我的第二个文件中,我需要记录它:
console.log(db)
我使用了导出和导入,但没有用:
export const db = mongoose.connection;
import db from (./db.js)
console.log(db)
我收到这个错误: 语法错误:无法在模块外使用导入语句
您是否也创建了 HTML 文件?如果是这样,请尝试将第二个文件作为模块类型加载以修复错误。
将此放入您的 HTML 文件中:
<script type="module" src="secondScript.js"></script>
在节点 js(或现代其他 js 平台)中,您可以使用模块。
在节点 js 中。你有2个选择。
1: 通用 js (CJS) 模块:
in a way, nodeJS based on CJS. and CJS modules builtin available in node.
you can imort a CJS module with this code :
const module = required("module file widout .js");
以及创建模块(在您的模块文件中):
module.export = {your code};
2 个 ES6 模块:
es6 is a newer version of JS and that supports modules defaultly.
使用模块:
你的例子:)(有问题post):
from module import a;
console.log(a); //1
创建模块:
export a = 1
对 ES6 模块非常重要: 你应该使用 js 编译器,比如 babel 将 es6-21 编译为 es5 nodeJS 和浏览器(我不知道其他平台)不支持es6或以上的JS版本。