daviddd

微信小程序之模块化

\'\'\'
官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/module.html
\'\'\'


可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块。模块只有通过 module.exports 或者 exports 才能对外暴露接口。

注意:

	- exports 是 module.exports 的一个引用,因此在模块里边随意更改 exports 的指向会造成未知的错误。所以更推荐开发者采用 module.exports 		
	来暴露模块接口,除非你已经清晰知道这两者的关系。
	
	
	- 小程序目前不支持直接引入 node_modules , 开发者需要使用到 node_modules 		时候建议拷贝出相关的代码到小程序的目录中,或者使用小程序支持的 npm 功能。

导入模块--common.js

//common.js

var studentList = [

	{
		name: "xiaoming",
		age: "22",
		hobby: "sleep"
	},
	{
		name: "xiaohong",
		age: "22",
		hobby: {
			one: "eat",
			two: "eatfood"
		}
 
	}
]
 
//模块化
module.exports = {
	studentList: studentList
}

//引入模块--index.js

var common = require("../aa/common.js")
//获取应用实例
var app = getApp()
Page({
  data: {
  },
   
  onLoad: function () {
	this.setData({
		studentList:common.studentList
		});
  }
})

官方示例 --导入函数(模块)

// common.js
function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}

module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye


# 在需要使用这些模块的文件中,使用 require 将公共代码引入

var common = require(\'common.js\')
Page({
  helloMINA: function() {
	common.sayHello(\'MINA\')
  },
  goodbyeMINA: function() {
	common.sayGoodbye(\'MINA\')
  }
})

分类:

技术点:

相关文章:

  • 2021-11-19
  • 2021-11-15
  • 2021-11-05
  • 2021-11-19
  • 2021-11-05
  • 2021-12-09
  • 2021-04-10
  • 2021-12-20
猜你喜欢
  • 2021-11-05
  • 2021-10-16
  • 2021-11-05
  • 2021-11-03
  • 2021-11-05
  • 2021-11-05
  • 2021-10-16
相关资源
相似解决方案