TypeScript入門,使用TypeScript編寫第三方控件的方式!


這是一篇新手篇的typescript插件編寫方式!!!!

源碼完整地址:https://gitee.com/dissucc/typescriptLearn

1.環境安裝

node下載

下載地址:https://nodejs.org/en/

cnpm安裝

在安裝完node后,npm默認就安裝了,因為某種原因,npm下載組件包的速度太慢了,所以需要安裝cnpm

安裝命令

 npm install -g cnpm --registry=https://registry.npm.taobao.org

推薦使用Vs Code開發

2.開發前的准備工作

a.新建一個文件夾,然后在vs code 中打開

ctrl+~喚起終端

輸入

npm install -g typescript

然后建一個基本的環境

好了,大概就是這個結構,我們今天要實現的就是一個帶額外提示的輸入框

效果圖如下

3.咱們開始吧!

首先,我們要寫的是一個基於AMD規范的插件,所以頁面代碼先這個樣子

  

<!DOCTYPE html>
<html>

<head>
    <title>TypeScript Greeter</title>
    <script src="https://cdn.bootcss.com/require.js/2.3.5/require.min.js"></script>
</head>

<body>
    <div class="box"></div>
</body>
<script>

</script>

</html>

先將requirejs引用到頁面

添加2個幫助類到項目里

element.ts

import _ from './unit';

export default class mElement {
    tagName: string;
    props: any;
    children: any;
    key: any;
    count: number;
    constructor(tagName: string, props: any, children: any[]) {
        if (!(this instanceof mElement)) {
            if (!_.isArray(children) && children != null) {
                children = _.slice(arguments, 2).filter(_.truthy)
            }
            return new mElement(tagName, props, children)
        }

        if (_.isArray(props)) {
            children = props
            props = {}
        }

        this.tagName = tagName
        this.props = props || {}
        this.children = children || []
        this.key = props
            ? props.key
            : void 666

        var count = 0

        _.each(this.children, function (child, i) {
            if (child instanceof mElement) {
                count += child.count
            } else {
                children[i] = '' + child
            }
            count++
        })

        this.count = count
    }
    render = function () {
        var el = document.createElement(this.tagName)
        var props = this.props

        for (var propName in props) {
            var propValue = props[propName]
            _.setAttr(el, propName, propValue)
        }

        _.each(this.children, function (child) {
            var childEl = (child instanceof mElement)
                ? child.render()
                : document.createTextNode(child)
            el.appendChild(childEl)
        })

        return el
    }
}

unit.ts

let _ = {
    type: function (obj) {
        return Object.prototype.toString.call(obj).replace(/\[object\s|\]/g, '')
    },

    isArray: function (list) {
        return this.type(list) === 'Array'
    },

    slice: function (arrayLike, index) {
        return Array.prototype.slice.call(arrayLike, index)
    },

    truthy: function (value) {
        return !!value
    },

    isString: function (list) {
        return this.type(list) === 'String'
    },

    each: function (array, fn) {
        for (var i = 0, len = array.length; i < len; i++) {
            fn(array[i], i)
        }
    },

    toArray: function (listLike: any[]) {
        if (!listLike) {
            return []
        }

        let list: any = []

        for (var i = 0, len = listLike.length; i < len; i++) {
            list.push(listLike[i])
        }

        return list
    },

    setAttr: function (node, key, value) {
        switch (key) {
            case 'style':
                node.style.cssText = value
                break
            case 'value':
                var tagName = node.tagName || ''
                tagName = tagName.toLowerCase()
                if (
                    tagName === 'input' || tagName === 'textarea'
                ) {
                    node.value = value
                } else {
                    // if it is not a input or textarea, use `setAttribute` to set
                    node.setAttribute(key, value)
                }
                break
            default:
                node.setAttribute(key, value)
                break
        }
    }
}
export default _;

看一下最終的項目結構

准備工作完成,開始編寫

input.ts

///input
export class Input <T extends InputOption>{
    private thatOption: T;
    //構造函數
    constructor(inputOption: T) {
        this.thatOption = inputOption;
    }
    //渲染方法
    render(ele) {
        console.log(this.thatOption)
    }
}

///配置項的接口
export interface InputOption {
    label?: string,
    placeholder?: string,
    extra?: string,
    value?: string
}

先將配置項輸出出來看看,有沒有問題!

XxxUI.ts

import { Input } from './base/input'
let XxxUI = {
    Input: (option) => {
        return new Input(option);
    }
}

export default XxxUI;

index.html ->script

<script>
    require(['XXXUI/XxxUI'], function (XxxUI) {
        var core = XxxUI.default;
        var input = core.Input({
            label: '測試',
            placeholder: '測試',
            extra: '測試',
            value: '1'
        });
        var box = document.querySelector(".box");
        input.render(box);
    })
</script>

編譯一下代碼

tsc src/XXXUI/XxxUI.ts -m amd

然后直接打開頁面看看是否有輸出

成功啦!開始寫東西,哈哈哈哈

插件最后生成的結構差不多是這個樣子的

 <div class='xui-input'>
    <label>測試</label>
    <input type="text"></input>
    <span>附加信息</span>
 </div>

先建一個文件,將創建DOM的操作封裝一層,要不然每次都要實例化,很麻煩

core.ts

import mElement from './element';


let ele: object;
export function create(tagName: string, props: any, children: any[]) {
    ele = new mElement(tagName, props, children);
    return ele;
}

然后修改我們的

input.ts

import { create } from './core';

///input
export class Input<T extends InputOption>{
    private thatOption: T;
    //構造函數
    constructor(inputOption: T) {
        this.thatOption = inputOption;

    }

    //渲染方法
    render(ele) {
        console.log(this.thatOption)
        const { label, placeholder, extra, value, click } = this.thatOption;
        const dom: any = create('div', { class: 'xui-input' }, [
            create('label', { type: 'text', onclick: click }, [label]),
            create('input', { placeholder, value }, undefined),
            create('span', undefined, [extra])
        ]);

        ele.appendChild(dom.render());
    }
}

///配置項的接口
export interface InputOption {
    label?: string,
    placeholder?: string,
    extra?: string,
    value?: string,
    click: string
}

這里演示了一下如何簡單的綁定事件!當然,你也可以換自己的寫法

index.html

 

<!DOCTYPE html>
<html>

<head>
    <title>TypeScript Greeter</title>
    <script src="https://cdn.bootcss.com/require.js/2.3.5/require.min.js"></script>
</head>

<body>
    <div class="box">
    </div>
</body>
<script>
    function onclicktest() {
        console.log(1);
    }
    require(['XXXUI/XxxUI'], function (XxxUI) {
        var core = XxxUI.default;
        var input = core.Input({
            label: '測試',
            placeholder: '測試',
            extra: '測試',
            value: '1',
            click: 'onclicktest()'
        });
        var box = document.querySelector(".box");
        input.render(box);
    })
</script>

</html>

看看頁面上的顯示

嗯,搞定了,這篇文章就這樣啦!

樣式什么的,我就不寫了,偷個懶偷個懶

是不是很簡單?快去寫個插件,封裝好,給自己使用吧!!!!!!!!!!!!

源碼地址:https://gitee.com/dissucc/typescriptLearn

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM