Docs Home / VS Code Extension / Explore with Playgrounds

Use require() in Playgrounds在游乐场中使用require()

You can use the require() function in your playgrounds to reuse code in your playgrounds. The code you include with require() can be either:您可以在游乐场中使用require()函数来重用游乐场中的代码。require()中包含的代码可以是:

Use Cases用例

Using require() to import code helps keep your playgrounds organized. If you are often performing the same tasks in your playgrounds, you can use require() to reuse code and avoid writing full functions in each of your playgrounds.使用require()导入代码有助于保持游乐场的有序性。如果你经常在操场上执行相同的任务,你可以使用require()重用代码,避免在每个操场上编写完整的函数。

For example, consider the following scenarios where reusing code can simplify logic and improve productivity:例如,考虑以下场景,重用代码可以简化逻辑并提高生产率:

  • You need to ensure that documents are inserted with a consistent structure. You can import a JavaScript file to validate the data format before the playground script performs the insert.您需要确保以一致的结构插入文档。在游乐场脚本执行插入操作之前,您可以导入一个JavaScript文件来验证数据格式。
  • You store monetary data and want to convert values between different currencies. You can import a JavaScript function to perform conversion calculations.您存储货币数据,并希望在不同货币之间转换值。您可以导入JavaScript函数来执行转换计算。
  • You need to import data from files on your local computer. You can use the native Node module fs to read data from local files.您需要从本地计算机上的文件导入数据。您可以使用本机Node模块fs从本地文件读取数据。

Get Started开始使用

To learn how to use require() in your playgrounds, see the following tutorials:要了解如何在操场上使用require(),请参阅以下教程: