0.3.1 • Published 8 months ago
plugin-inject-vue v0.3.1
plugin-inject-vue
Vue 全局注入组件(Webpack loader)
安装
pnpm add -D plugin-inject-vue
配置项
参数 | 类型 | 描述 |
---|---|---|
type | 'parent'|'children'|'slot' | 插入节点类型 |
position | 'before'|'after' | 组件插入位置。作为子节点时必传 |
slot | string | type 为 'slot' 时必填 |
test | RegExp|(filePath: string) => boolean | 测试文件是否需要注入 |
component | { name: string } | 组件配置 |
示例
作为父容器插入
- 新建容器组件
/src/components/Container.vue
<template>
<view>公共部分</view>
<!-- 必须存在 default slot,匹配的 .vue 文件中 template 内容将被插入此处 -->
<slot />
</template>
- 全局注册组件
/src/app.js
import Container from './components/Container.vue';
createApp().component('Container', Container);
- 修改 Webpack 配置
WebpackChain 示例
chain.module.rule('vue')
.use('template-loader')
.loader('plugin-inject-vue')
.options({
type: 'parent',
test: (filePath) => {
return /\.vue$/.test(filePath) && /pages\//.test(filePath) && !/components\//.test(filePath);
},
component: {
// name 为上面全局注册的组件名
name: 'Container'
},
})
// 必须配置在 vue-loader 之后
.after('vue-loader');
假设将匹配的文件内容
<template>
<view>单文件内容</view>
</template>
最终效果为
<template>
<Container>
<!-- 原文件内容 -->
<view>单文件内容</view>
</Container>
</template>
使用 <slot> 方式注入
- 新建组件
/src/components/Hello.vue
<template>
<view>Hello {{ nickname }}!</view>
</template>
<script>
export default {
props: {
nickname: { type: String, default: '' },
},
}
</script>
- 全局注册组件
/src/app.js
import Hello from './components/Hello.vue';
createApp().component('Hello', Hello);
- 修改 Webpack 配置
chain.module.rule('vue')
.use('template-loader')
.loader('plugin-inject-vue')
.options({
type: 'slot',
// type 为 'slot' 时必填
slot: 'hi',
test: (filePath) => {
return /\.vue$/.test(filePath) && /pages\//.test(filePath) && !/components\//.test(filePath);
},
component: {
// name 为上面全局注册的组件名
name: 'Hello'
},
})
// 必须配置在 vue-loader 之后
.after('vue-loader');
假设将匹配的文件内容
<template>
<view>你在楼上看风景</view>
<slot name="hi" nickname="小红" />
<view>我在楼下看你</view>
<slot name="hi" nickname="小明" />
</template>
最终效果为
<template>
<view>你在楼上看风景</view>
<Hello name="hi" nickname="小红" />
<view>我在楼下看你</view>
<Hello name="hi" nickname="小明" />
</template>
Vite
import { defineConfig } from 'vite'
import vueInject from 'plugin-inject-vue/rollup'
import uni from '@dcloudio/vite-plugin-uni'
export default defineConfig({
plugins: [
// vueInject 必须在 vue 插件之前
vueInject({
test: (id) => {
const matched = /pages.*\.vue$/.test(id)
return matched
},
component: { name: 'PageLayout' }
}),
uni(),
],
})
Vue2
需要额外安装 @vue/compiler-sfc
pnpm add -D @vue/compiler-sfc
从 v0.2.0 开始不再需要如下配置,和 Vue3 一样的使用方式
插件配置改为
chain.module.rule('vue')
.use('template-loader')
// 注意此处做了修改
.loader('plugin-inject-vue/dist/vue2.cjs')
.options({
test: (filePath) => {
return /\.vue$/.test(filePath) && /pages\//.test(filePath) && !/components\//.test(filePath);
},
component: {
name: 'Container'
},
})
// 必须配置在 vue-loader 之后
.after('vue-loader');