JavaScript 模块切换方法:import/export 和 require/module.exports
要在 JavaScript 中切换模块,可以使用以下几种方法:\n\n1. 使用 import 和 export 关键字:在模块中使用 export 关键字将变量、函数或类导出,然后在另一个模块中使用 import 关键字引入这些导出的内容。\n\n例如,在一个名为 module1.js 的模块中导出一个变量和一个函数:\n\njavascript\n// module1.js\nexport const variable = \"Hello\";\nexport function greeting(name) {\n console.log(`Welcome, ${name}!`);\n}\n\n\n然后在另一个模块中使用 import 引入这些导出的内容:\n\njavascript\n// module2.js\nimport { variable, greeting } from './module1.js';\n\nconsole.log(variable); // 输出 \"Hello\"\ngreeting(\"Alice\"); // 输出 \"Welcome, Alice!\"\n\n\n2. 使用 require 和 module.exports:在旧版本的 JavaScript 中,可以使用 require 函数来引入模块,并使用 module.exports 来导出内容。\n\n例如,在一个名为 module1.js 的模块中导出一个变量和一个函数:\n\njavascript\n// module1.js\nconst variable = \"Hello\";\nfunction greeting(name) {\n console.log(`Welcome, ${name}!`);\n}\n\nmodule.exports = {\n variable,\n greeting\n};\n\n\n然后在另一个模块中使用 require 引入这些导出的内容:\n\njavascript\n// module2.js\nconst { variable, greeting } = require('./module1.js');\n\nconsole.log(variable); // 输出 \"Hello\"\ngreeting(\"Alice\"); // 输出 \"Welcome, Alice!\"\n\n\n无论是使用 import/export 还是 require/module.exports,都需要在支持模块的环境中运行代码,如 Node.js 或现代浏览器。
原文地址: https://www.cveoy.top/t/topic/pQdo 著作权归作者所有。请勿转载和采集!