前言
- 使用tsdx进行项目初始化,这个库可以解决大部分ts打包成库的配置设置问题,对于不会配置的小伙伴及其友好(基本上都配置完了)
- 自动生成example文件,也不需要对webpack进行配置了
- 因为项目需求需要打包发布npm,发布完成后学习的过程来这里记录一下
Git官网
https://github.com/jaredpalmer/tsdx#quick-start
正文
- 初始化项目
npx tsdx create mylib //mylib是初始化项目名称
- 会出现三个选项供你选择,这里我选的是react
- 完成初始化后的目录,dist目录是打包后的文件目录,example是实例目录,可以在里面实时调用你已经封装好的组件或者方法,确认无误后再打包发布等等,src就是主文件目录了
- src文件目录结构(lib是封装组件的目录,index文件为暴露组件文件)
- index文件将组件抛出
- index.config.ts配置文件,因为打包是不支持scss,less和svg的,所以如果要使用的话,需要配置转换,需要在index.config.ts和tsdx.config.js中配置
//index.config.ts配置文件
declare module '*.less' {
const content: any;
export default content;
}
declare module '*.scss' {
const content: any;
export default content;
}
declare module '*.svg' {
import * as React from "react";
export const ReactComponent: React.FunctionComponent<
React.SVGProps<SVGSVGElement> & { title?: string }
>;
const src: string;
export default src;
}
//tsdx.config.js配置文件
const postcss = require('rollup-plugin-postcss');
// const autoprefixer = require('autoprefixer');
const image = require('@rollup/plugin-image');
const json = require('@rollup/plugin-json')
// const cssnano = require('cssnano');
module.exports = {
configureWebpack: {
module: {
rules: [
{
test: /\.geojson$/,
loader: 'json-loader'
}
]
},
},
rollup(config, options) {
config.plugins.push(
json({
kml: true
}),
postcss({
// plugins: [
// autoprefixer(),
// cssnano({
// preset: 'default',
// }),
// ],
inject: true, // 是否主动注入css到js中(设置为true,则在引用组件的时候,就无需再单独引入css了)
extract: !!options.writeMeta, //
// modules: true, // 使用css modules
camelCase: true, // 支持驼峰
sass: true, // 是否使用sass
less: true, // 是否使用less
}),
);
// 截至2021年3月: 必须使用 unshift 添加 image 插件, 否则报错
config.plugins.unshift(image({
svg: true
}));
return config;
},
};
项目启动和运行
- 需要打开两个终端,一个是项目的根目录,还有一个是通过cd example进入example目录下
- 通过yarn start就会进行编译和运行,成功启动后在http://localhost:1234(默认的)页面中看到自己封装的组件效果,运行成功状态如下:
- 注意:初始化项目的时候需要在根目录和example终端分别yarn一下安装依赖
打包和发布到npm
- 通过yarn build 打包组件
- 根目录下package.json中的配置,version就是发布组件的版本,license是认证这个就填MIT(麻省理工)就可以了,name是你的组件包的名称
安装的配置文件(可参考):
- 打包成功后的dist文件目录
- 在终端运行npm login 登录npm账号,按照提示输入username、password、email,登录后,可以通过npm whoami来查看登录用户信息
npm whoami //查看当前登录的npm用户
- 发布到npm
npm push --access=public
可能遇到的问题
- 打包发布可能会遇到命名重复问题,只要修改name再次打包发布就可以了
- 开发途中还遇到了不少问题,但具体很多都忘记了,所以评论区可以交流交流打包发布过程遇到的问题
- 以及文章中有不对的地方请指正