场景需求:项目B引入项目A的内容或引用项目A中的某个组件
一、组件A导出配置
- 项目A:
./src/ComponentA/index.vue
<template>
<div>组件A</div>
</template>
<script>
export default {
name: 'ComponentA',
components: {},
props: {},
data() {
return {};
},
mounted() {},
methods: {}
};
</script>
<style></style>
- 项目A:
./src/ComponentA/index.ts
// 引入组件ComponentA(组件的name名字需和导出的名字一致)
import ComponentA from './ComponentA/index.vue';
const components = [ComponentA];
const install = function (Vue) {
// 注册组件
components.forEach(item => {
Vue.component(item.name, item); //
});
};
// 如果是直接引入文件,就不用调用Vue.use()
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
export default { install }; // 必须要有导出
export { ComponentA as ComponentA };
二、插件打包
(一)安装
使用插件:FileManagerPlugin
安装:npm install filemanager-webpack-plugin --save-dev
(二)使用
场景需求:需要将项目A(或项目A中的某个组件,如组件A)打包后的dist文件复制到项目B的指定文件夹(folderB)下
- 项目A:
webpack.config.js
// 引入插件 FileManagerPlugin
const FileManagerPlugin = require('filemanager-webpack-plugin');
module.exports = {
entry: {
'projectA-dist': './src/index.ts', //整个项目A的文件打包入口;
'projectA-ComponentA-dist': './src/ComponentA/index.ts' //单独打包项目A中的组件A;
},
output: {
clean: true,
filename: '[name].umd.js', //打包之后的名字就是entry中的key的名字
path: path.resolve('dist'),
//?
library: {
type: 'umd',
name: '[name]'
}
},
// ..
plugins: [
new FileManagerPlugin({
events: {
onStart: {
delete: [
{
// 绝对路径
source: 'D:/projectB/src/folderB/dist/*', //先从项目B的folderB文件夹中删除之前打包的'projectA-dist'等文件
options: {
force: true
}
}
]
},
onEnd: {
copy: [
{
source: './dist/*', //当前项目A的dist文件夹下的文件(不包括文件夹)
destination: 'D:/projectB/src/folderB/dist/*' //复制到项目B的指定文件夹folderB下
},
{
source: './dist/img', // 当前项目A的dist文件夹下的img文件夹
destination: 'D:/projectB/src/folderB/dist/img' //复制到项目B的指定文件夹folderB下的img文件夹
}
]
}
}
})
]
};
- 项目B:打包后项目B中会出现folderB文件夹和项目A中打包的文件
三、在项目B中使用打包后的组件A
- 项目B:
test.vue
<template>
<div>
<ComponentA ref="componentARef"></ComponentA>
</div>
</template>
<script>
import { Component, Vue } from 'vue-property-decorator'; //引用打包的组件需要引入Component, Vue
// 使用项目A中的组件A
import ComponentA from '@/folderB/dist/projectA-ComponentA-dist.umd.js';
import '@/folderB/dist/projectA-ComponentA-dist.css';
Vue.use(ComponentA);
// 使用项目A
// import projectA from '@/folderB/dist/projectA-dist.umd.js';
// import '@/folderB/dist/projectA-dist.css';
// Vue.use(projectA);
export default {
props: {},
data() {
return {};
},
mounted() {},
methods: {}
};
</script>
<style></style>