简简单单发布一个npm包

170 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

昨天搞了一个复制时自动增加小尾巴的脚本,今天一个人没给我点赞。我不服,我要发布到npm上供自己使用。

首先初始化项目

npm init -y
tsc --init 

生成了package.json和ts.config.js ,修改ts.config.js中配置中module属性值为“ESNext”.

安装依赖

yarn add rollup-plugin-clear rollup rollup-plugin-dts rollup-plugin-typescript2  typescript -D

rollup 和 webpack同样式打包工具,更加轻量。 rollup-plugin-clear 清空dist目录用的插件 rollup-plugin-typescript2 自动为文件中的变量生成ts声明文件。

创建rollup.config.js,添加打包配置

import path from 'path'
import ts from 'rollup-plugin-typescript2'
import dts from 'rollup-plugin-dts'
import clear from 'rollup-plugin-clear'
export default [{
    input: "./src/core/index.ts",
    output: [{
        file: path.resolve(__dirname, './dist/index.esm.js'),
        format: "es",
    }, {
        file: path.resolve(__dirname, './dist/index.cjs.js'),
        format: "cjs"
    }, {
        file: path.resolve(__dirname, './dist/index.js'),
        format: "umd",
        name: "Clipboard"
    }],
    plugins: [clear({
            targets: ["dist"]
        }),
        ts({
            include: "src/**/*.ts",
            exclude: "node_modules/**",
        }),
    ]
}, {
    input: "./src/core/index.ts",
    output: {
        file: path.resolve(__dirname, './dist/index.d.ts'),
        format: 'es',
    },
    plugins: [dts()]
}]

打包2次,一次是,生成项目的各种格式的模块。一次打包所有的可以支持的产物格式 第二次到包,到包所有ts到dist/目录下。

配置build脚本,和npm上的入口配置

在package.json中增加script脚本。增加🧍‍各个模块引用模式的入口文件,file属性是配置入口文件所在目录查找的优先级

  "main": "dist/index.cjs.js",
  "module": "dist/index.esm.js",
  "browser": "dist/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "rollup -c"
  },
  "keywords": [
    "clipboard",
    "小尾巴",
    "版权",
    "复制",
    "粘贴"
  ],
  "files": [
    "dist"
  ],

写代码

创建文件src/core/index.ts,写下核心代码


import { DefaultOptions, Options } from "../types/index";

export default class MyClipboard {
    data: DefaultOptions & Options;
    constructor(options = {} as Options) {
        this.data = Object.assign(this.initDef(), options);
        this.initClipboard();
    }
    private initClipboard() {
        let node = document.querySelector(this.data.select as keyof HTMLElementTagNameMap) as HTMLElement;
        node.addEventListener('copy', (e) => {
            this.setClipboard(e);
        });
    }
    setClipboard(event: ClipboardEvent) {
        event.preventDefault();
        var node = document.createElement('div');
        node.appendChild((window as any).getSelection().getRangeAt(0).cloneContents());
        //getRangeAt(0)返回对基于零的数字索引与传递参数匹配的选择对象中的范围的引用。对于连续选择,参数应为零。
        var htmlData = `<div>${node.innerHTML}${this.data.html}</div>`;
        var textData = (window as any).getSelection().getRangeAt(0) + this.data.text;
        if (event.clipboardData) {
            // html是数据拷贝到富文本时的值
            event.clipboardData.setData("text/html", htmlData);
            //setData(剪贴板格式, 数据) 给剪贴板赋予指定格式的数据。返回 true 表示操作成功。
            event.clipboardData.setData("text/plain", textData);
        } else if ((window as any).clipboardData) {
            //window.clipboardData的作用是在页面上将需要的东西复制到剪贴板上,提供了对于预定义的剪贴板格式的访问,以便在编辑操作中使用。
            return (window as any).clipboardData.setData("text", textData);
        }
    }
    private initDef(): DefaultOptions {
        return <DefaultOptions>{
            select: "body",
            html: `著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。作者:<a href="https://juejin.cn/user/3685218708368519">李老汉</a><br />来源: <a href="https://juejin.cn/user/3685218708368519">瑞旗家园604</a>`,
            text: "\n\n著作权归作者所有。\n商业转载请联系作者获得授权,非商业转载请注明出处。\n作者:李老汉\n来源:瑞旗家园604"
        }
    }
}

在src/types/index.ts中配置项目中定义的属性

export interface DefaultOptions {
    select: keyof HTMLElementTagNameMap | undefined, // 选择器
    html: string | undefined,
    text: string | undefined,
}

export interface Options extends Partial<DefaultOptions> {
}

export enum ClipboardConfig {
    version = "1.0.0"
}

注册npm账号,并且得到账号名和密码。

配置全局username和邮箱。login

npm login 

// 输入用户名
//输入密码
// 输入端短信信息

##发布了


npm publish 

这种简单的工具化的组件。完全可发布一个npm包,供以后使用。

安装

npm install clipboard-sdk

使用

import Clipboard from 'clipboard-sdk';


new Clipboard(select,html,text);

select是选择器。不传默认是body. html复制到富文本时追击的版权信息 text复制到文本区域追加版权信息