vue3+ts 开发组件库

1,394 阅读1分钟

架构参考element-ui

image.png

tsconfig.json

  • Typescript项目配置文件
  • 命令行执行tsc后,会根据该配置文件将项目中的ts编译为js
选项类型默认值描述
--declaration -dbooleanfalse生成相应的 .d.ts文件。
--declarationDirstring生成声明文件的输出路径。
--sourceMapbooleanfalse生成相应的 .map文件。

vue.shim.d.ts

/**
* vue.shim.d.ts的作用 
* 为了typescript做的适配定义文件,因为.vue文件不是一个常规的文件类型,*  ts是不能理解* vue文件是干嘛的,
* 加这一段是告诉ts,vue文件是这种类型。
* 可以把这一段删除,会发现import的所有vue类型的文件都会报错。
**/
declare module '*.vue' {
    import { App, defineComponent } from 'vue'
    const component: ReturnType<typeof defineComponent> & {
        install(app: App) : void
    }
    export default component
}

package.json配置vue

"peerDependencies": {
    "vue": "^3.0.9"
  },
  • peerDependencies的目的是提示宿主环境去安装满足插件peerDependencies所指定依赖的包,然后在插件import或者require所依赖的包的时候,永远都是引用宿主环境统一安装的npm包,最终解决插件与所依赖包不一致的问题。
  • 白话:假如组件库工程安装了vue,业务项目工程中也安装了vue;代码运行时,组件库和业务项目各自调用的vue不是同一个,导致参数传递失败。

webpack配置文件配置babel-loader,处理ts、es6

            {
                    test: /\.(ts|js)x?$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            '@babel/preset-env',[
                                '@babel/preset-typescript',
                                {
                                    allExtensions: true
                                }
                            ]
                        ]
                    }
                }

组件库发布到npm

  1. 根目录新增.npmignore文件
  2. .npmignore文件内写入需要忽略的文件和文件夹
.vscode
build
node_modules
packages
test
typings
.gitignore
.npmignore
jest.config.js
tsconfig.json
  1. 命令行执行npm publish

上传代码到github

  1. 根目录新增.gitignore文件
  2. .gitignore文件内写入不需要上传的文件和文件夹