Underscore.js를 이용한 미니프로그램 개발에 대한 자세한 설명

零下一度
풀어 주다: 2017-05-26 10:32:22
원래의
2926명이 탐색했습니다.

Underscore.js가 함수형 프로그래밍을 위한 실용적인 기능 세트를 제공하지만 JavaScript 내장 개체를 확장하지는 않는 JavaScript 도구 라이브러리라는 것은 누구나 알고 있습니다. 따라서 이 글에서는 WeChat 애플릿에서 타사 라이브러리인 Underscore.js를 사용하는 방법을 알아보겠습니다. 필요한 경우 참조할 수 있습니다.

머리말

Underscore.js는 압축 후 크기가 4KB에 불과한 매우 간결한 라이브러리입니다. Underscore는 일반적으로 사용되는 기능인 map, 필터, 호출 등 100개 이상의 기능을 제공합니다. 물론 함수 바인딩, JavaScript 템플릿 기능, 빠른 인덱스 생성, 강력한 유형 평등 테스트와 같은 보다 전문적인 보조 기능도 제공합니다. 그리고 더. 이는 표준 라이브러리의 단점을 보완하고 JavaScript 프로그래밍을 크게 촉진합니다.

WeChat 애플릿은 require( 'underscore.js' )를 사용하여 직접 호출할 수 없습니다.

WeChat 애플릿 모듈화 메커니즘

WeChat 애플릿 실행 환경은 CommoJS 모듈화를 지원하고 module.exports를 통해 객체를 노출합니다. 필요하다.

WeChat 미니 프로그램 빠른 시작 utils/util.js

function formatTime(date) {
 var year = date.getFullYear()
 var month = date.getMonth() + 1
 var day = date.getDate()

 var hour = date.getHours()
 var minute = date.getMinutes()
 var second = date.getSeconds();


 return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
 n = n.toString()
 return n[1] ? n : '0' + n
}

module.exports = {
 formatTime: formatTime
}
로그인 후 복사

pages/log/log.js

var util = require('../../utils/util.js')
Page({
 data: {
 logs: []
 },
 onLoad: function () {
 this.setData({
 logs: (wx.getStorageSync('logs') || []).map(function (log) {
 return util.formatTime(new Date(log))
 })
 })
 }
})
로그인 후 복사

이유 분석

Underscore CommonJs 모듈 내보내기 코드는 다음과 같습니다.

// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
 if (typeof module !== 'undefined' && module.exports) {
 exports = module.exports = _;
 }
 exports._ = _;
} else {
 root._ = _;
}
로그인 후 복사

내보내기 및 모듈을 내보내기 전에 정의해야 합니다. 테스트를 통해 WeChat 애플릿 실행 환경 내보내기 및 모듈이 정의되지 않았습니다

//index.js

//获取应用实例
var app = getApp();

Page({ 

 onLoad: function () {
 console.log('onLoad');
 var that = this;

 console.log('typeof exports: ' + typeof exports); 
 console.log('typeof module: ' + typeof exports); 

 var MyClass = function() {

 }

 module.exports = MyClass;

 console.log('typeof module.exports: ' + typeof module.exports); 
 }
})
로그인 후 복사

해결 방법

Underscore 코드를 수정하고 원래 모듈 내보내기 문에 주석을 달고 module.exports = _ 를 사용하여 강제로 내보내기

 /*
 // Export the Underscore object for **Node.js**, with
 // backwards-compatibility for the old `require()` API. If we're in
 // the browser, add `_` as a global object.
 if (typeof exports !== 'undefined') {
 if (typeof module !== 'undefined' && module.exports) {
 exports = module.exports = _;
 }
 exports._ = _;
 } else {
 root._ = _;
 }
 */

 module.exports = _;
로그인 후 복사
rrree

Underscore.js 사용

 /*
 // AMD registration happens at the end for compatibility with AMD loaders
 // that may not enforce next-turn semantics on modules. Even though general
 // practice for AMD registration is to be anonymous, underscore registers
 // as a named module because, like jQuery, it is a base library that is
 // popular enough to be bundled in a third party lib, but not be part of
 // an AMD load request. Those cases could generate an error when an
 // anonymous define() is called outside of a loader request.
 if (typeof define === 'function' && define.amd) {
 define('underscore', [], function() {
 return _;
 });
 }
 */
로그인 후 복사

요약

위는 타사 라이브러리 Underscore.js를 사용하는 WeChat 애플릿의 전체 내용입니다. 모든 사람의 학습에 도움이 되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨서 소통하세요.

[관련 추천]

1. WeChat 개발에서 글로벌 JS를 호출하는 방법은 무엇인가요?

2. WeChat 개발의 JS 동적 수정 스타일

3. WeChat 개발 시 다른 js 파일을 참조하는 예시에 대한 자세한 설명

4. 위챗 개발의 라이프사이클 기능 튜토리얼 예시

위 내용은 Underscore.js를 이용한 미니프로그램 개발에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!