npm包发布
vite打包lib库分析
项目结构
bash
# packages项目结构
├── vite.config.ts # vite配置文件
├── packages
├── index.ts # 入口文件
└── index.css
└── libs # 工具函数
└── index.js
└── components # 组件文件
└── comA
└── index.vue
└── index.ts
└── index.css
└── comB
└── index.vue
└── index.ts
└── index.css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
comA/index.ts代码:
ts
import ComA from './index.vue';
export {
ComA,
}
1
2
3
4
2
3
4
packages/index.ts代码:
ts
import type { App } from 'vue';
import { ComA } from './components/comA';
import './index.css'
// 可以引入其他工具函数
import { myUtils } from './libs/index.js';
const components: any[] = [ComA];
const install = (app: App): void => {
components.forEach((component) => {
app.component(component.name, component);
});
};
export { ComA, myUtils }
export default {
install,
myUtils,
...components,
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
vite.config.ts代码:
ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
// 打包配置
build: {
lib: {
entry: 'src/packages/index.ts', // 设置入口文件
name: 'xxx-lib', // 起个名字,安装、引入用
fileName: (format) => `vite-lib.${format}.js` // 打包后的文件名
},
sourcemap: true, // 输出.map文件
rollupOptions: {
// 确保外部化处理那些你不想打包进库的依赖
external: ['vue', 'ant-design-vue'],
output: {
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
vue: 'Vue',
'ant-design-vue': 'ant-design-vue'
}
}
}
},
plugins: [vue()],
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
additionalData: '@import "./src/packages/index.css";',
}
}
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
发布安装后使用:
vue
<template>
<com-a></com-a>
</template>
<script setup lang="ts">
import { ComA, myUtils } from 'xxx-lib';
console.log(myUtils);
</script>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9