# Cloud function public module

Cloud functions support public modules. The shared parts of multiple cloud functions can be extracted into common modules and then referenced by multiple cloud functions.

Version requirements: HBuilderX 2.6.6+

Take the following directory structure as an example to introduce how to use it.

cloudfunctions
  ├─common // 云函数公用模块目录
  |  └─hello-common // 云函数公用模块
  |     ├─package.json
  |     └─index.js // 公用模块代码,可以不使用index.js,修改 package.json 内的 main 字段可以指定此文件名
  └─use-common // 使用公用模块的云函数
     ├─package.json // 在 use-common 目录执行 npm init -y 生成
     └─index.js // 云函数入口文件

Create and import common modules

  1. Create a common directory under the cloudfunctions directory
  2. Right-click on the common directory to create a common module directory (in this case, hello-common, see the example below), the entry index.js file and package.json will be created automatically, Do not modify The name field of this package.json
  3. hello-common右键上传公用模块
  4. 在云函数上右键选择管理公共模块依赖,添加依赖的公共模块

管理公共模块依赖

Public modules depend on other public modules in the same way

Create a common module

Precautions

  • If you want to update all cloud functions that depend on a common module, you can right-click on the public module directory (in this case, hello-common) under the common directory and select Update cloud functions that depend on this module
  • 公用模块命名不可与nodejs内置模块重名
  • Importing from the plugin market or copying projects from other places may cause the soft links created by npm install to become invalid. If this happens, delete node_modules and package-lock.json and re npm install

Update common module

Using common modules

Still taking the above directory as an example, exports in the public module and require in the cloud function can be used. The sample code is as follows:

// common/hello-common/index.js
function getVersion() {
  return '0.0.1'
}
module.exports = {
  getVersion,
  secret: 'your secret'
}
// use-common/index.js
'use strict';
const {
  secret,
  getVersion
} = require('hello-common')
exports.main = async (event, context) => {
  let version = getVersion()
  return {
    secret,
    version
  }
}

If you only need to export a function, you can also use the following writing

// common/hello-common/index.js
module.exports = function(e){
  return e
}
// use-common/index.js
'use strict';
const echo = require('hello-common')
exports.main = async (event, context) => {
  let eventEcho = echo(event)
  return {
    eventEcho
  }
}