在以前的前端技术发展中是没有模块的概念,早期的开发中,如果要实现模块化的使用,是要通过script标签引入才能使用,但是不可避免要想使用不同的标签内的变量或者封装好的插件,则需要将构造函数或者变量通过window来进行暴露,但是就用了弊端,如果多人开发,同时变量名冲突的情况下就很难解决
于是就用了common.js使用require来进行解决,在ES6后,JS有了export和import来进行导出和导入,模块化的开发也是未来发展的趋势
因为JS语言的发展不局限于单单的前端,还想走更远,对标不同的语言
ps.相信你在阅读这篇文章之前已经回应用Vue或者node进行开发了,这篇文章是html通过script标签使用模块
废话不多说,马上开始
按钮倒计时
/**
* 倒计时功能
*/
;(function (w) {
function ButtonSetTime(ele) {
this.element = document.getElementById(ele);
};
/**
*
* @param {初始化obj} obj
*/
ButtonSetTime.prototype.init = function (obj) {
this.index = obj.index;
this.start = obj.start || "获取验证码";
this.during = obj.during || '秒后重新获取..';
this.end = obj.end || this.start;
this.element.innerHTML = this.start;
this.edge=obj.index;
var that = this;
this.element.onclick = function () {
that.element.setAttribute('disabled', true);
that.element.innerHTML=that.index+that.during;
var timeId = setInterval(function () {
that.index--;
if(that.index==0) {
clearInterval(timeId);
that.element.innerHTML=that.end;
that.element.removeAttribute('disabled');
that.index=obj.index;
}else {
that.element.innerHTML=that.index+that.during;
}
}, 1000);
if(obj.fn) {
that.fn(obj.fn);
}
}
}
/**
*
* @param {回调函数} fn
*/
ButtonSetTime.prototype.fn=function(fn) {
fn();
}
w.buttonSetTime = function (ele) {
return new ButtonSetTime(ele);
}
}(window));
/**
* 倒计时功能
*/
function ButtonSetTime(ele) {
this.element = document.getElementById(ele);
}
/**
*
* @param {初始化obj} obj
*/
ButtonSetTime.prototype.init = function (obj) {
this.index = obj.index;
this.start = obj.start || "获取验证码";
this.during = obj.during || '秒后重新获取..';
this.end = obj.end || this.start;
this.element.innerHTML = this.start;
this.edge = obj.index;
var that = this;
this.element.onclick = function () {
that.element.setAttribute('disabled', true);
that.element.innerHTML = that.index + that.during;
var timeId = setInterval(function () {
that.index--;
if (that.index == 0) {
clearInterval(timeId);
that.element.innerHTML = that.end;
that.element.removeAttribute('disabled');
that.index = obj.index;
} else {
that.element.innerHTML = that.index + that.during;
}
}, 1000);
if (obj.fn) {
that.fn(obj.fn);
}
}
}
/**
*
* @param {回调函数} fn
*/
ButtonSetTime.prototype.fn = function (fn) {
fn();
}
var buttonSetTime = function (ele) {
return new ButtonSetTime(ele);
}
export default buttonSetTime;
var path = require('path');
module.exports = {
mode: 'development',
entry: './test.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
8.创建一个test.js的文件,这个文件导入buttonSetTime.js文件,并且写上业务处理代码
import buttonSetTime from './buttonSetTime'
buttonSetTime('btn').init({
index: 5,
start: '获取验证码',
during: '秒后重新获取..',
end: '重新获取'
})
9.在根目录下运行终端,
webpack命令’’
10.webpack会生成一个dist文件,里面就有一个js文件
Document