美文网首页Vue.js
vue-cli 3.x 发布 npm 组件库

vue-cli 3.x 发布 npm 组件库

作者: bei6 | 来源:发表于2019-10-14 17:14 被阅读0次

    vue-cli 3.x 发布 npm 组件库

    整体流程

    1. 使 component 支持以插件的形式导出
    2. 配置 package.json 中包的关键信息、打包命令
    3. 配置 .npmignore 文件
    4. 打包、发布

    写插件组件

    首先 vue create 一个新项目,正常配置即可。

    然后再 src/components 目录下新建一个文件夹 wellcome,它看起来像是这样的:

    wellcome
      │  index.js
      │
      └─src
            data.json
            main.vue
    

    src/: 存放组件的相关代码

    index.js: 支持将单组件作为插件导出

    import Wellcome from './src/main';
    
    // 按需引入的代码,支持单个导入
    export default {
      install(Vue, options) {
        Vue.component(Wellcome.name, Wellcome);
      },
    };
    

    不过当我们编写的插件组件越来越多的时候,每个组件都引入以下还是很烦的,所以,一个整体引入也是需要的。

    在 src/components/ 目录下新建一个 index.js 文件,内容如下:

    import Textarea from './textarea/index';
    
    // 以数组的结构保存组件,便于遍历
    const components = [Textarea];
    
    // 引入全部组件
    const install = function(Vue) {
      if (install.installed) return;
      install.installed = true;
      // 遍历并注册全局组件
      components.map(component => {
        Vue.component(component.name, component);
      });
    };
    
    if (typeof window !== 'undefined' && window.Vue) {
      install(window.Vue);
    }
    
    export default {
      install,
      ...components,
    };
    

    package.json

    name: 项目名称

    version: 版本

    description: 项目描述

    main: 入口文件

    private: 是否私有

    license: 许可

    author: 作者

    scripts: 配置 npm 脚本

    scripts: 添加两个命令,b(build)、p(publish)

    b 指令中一般情况下只需要修改 --name 后面的参数即可,改参数决定了构建后的输出文件的名称。

    --target lib: 库模式
    -- name dcom: 输出文件名
    -- dest lib: 输出目录
    src/components/index.js: 入口文件

    "name": "@docimax/components",
    "version": "0.0.1",
    "description": "docimax components plugin",
    "main": "lib/dcom.umd.min.js",
    "private": false,
    "license": "MIT",
    "author": "bei <liub@docimax.com.cn>",
    "scripts": {
      "serve": "vue-cli-service serve",
      "b": "vue-cli-service build --target lib --name dcom --dest lib src/components/index.js",
      "p": "npm publish --access public"
    },
    

    .npmignore

    忽略一些文件

    node_modules/
    public/
    vue.config.js
    babel.config.js
    *.map
    *.html
    
    # local env files
    .env.local
    .env.*.local
    
    # Log files
    npm-debug.log*
    yarn-debug.log*
    yarn-error.log*
    
    # Editor directories and files
    .idea
    .vscode
    *.suo
    *.ntvs*
    *.njsproj
    *.sln
    *.sw*
    

    build & publish

    npm run b
    npm run p
    

    相关文章

      网友评论

        本文标题:vue-cli 3.x 发布 npm 组件库

        本文链接:https://www.haomeiwen.com/subject/iukrmctx.html