项目用到vue3、element-plus,使用vite构建,自定义主题,记录如下:
1、搭建一个vite + vue项目
# npm 6.x
npm create vite@latest my-vue-app --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue
2、进入my-vue-app项目目录下,安装Element Plus
cd my-vue-app
# NPM
$ npm install element-plus --save
element-plus使用SCSS编写,安装sass
npm install sass -D
3、设置项目自动按需导入Element Plus组件
首先需要安装unplugin-vue-components 和 unplugin-auto-import这两款插件
npm install -D unplugin-vue-components unplugin-auto-import
4、自定义主题
新建一个样式文件,例如 style/index.scss,自定义主题
// style/index.scss
@forward 'element-plus/theme-chalk/src/common/var.scss' with (
$colors:(
'white': #ffffff,
'black': #000000,
'primary': (
'base': #17A7FF, // 修改primary base color
),
'success': (
'base': #67c23a,
),
'warning': (
'base': #e6a23c,
),
'danger': (
'base': #f56c6c,
),
'error': (
'base': #f56c6c,
),
'info': (
'base': #909399,
),
),
$font-size:(
'extra-large': 20px,
'large': 18px,
'medium': 16px,
'base': 14px,
'small': 13px,
'extra-small': 12px,
)
);
5、vite.config.js中增加配置
注意ElementPlusResolver({ importStyle: 'sass' }),需要importStyle配置样式引入方式,不然自定义主题无效
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { fileURLToPath, URL } from 'node:url'
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver({ importStyle: 'sass' })],
imports: [
'vue',
'vue-router',
'pinia',
{
'@vueuse/core': [
// named imports
'useMouse', // import { useMouse } from '@vueuse/core',
// alias
['useFetch', 'useMyFetch'] // import { useFetch as useMyFetch } from '@vueuse/core',
],
axios: [
// default imports
['default', 'axios'] // import { default as axios } from 'axios',
]
}
], //自动引入vue的ref、toRefs、onmounted等,无需在页面中再次引入
eslintrc: {
enabled: true
}
}),
Components({
resolvers: [ElementPlusResolver({ importStyle: 'sass' })]
}),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/style/index.scss" as *;`
}
}
},
base: './',
build: {
outDir: 'dist',
minify: 'esbuild',
target: 'es2015',
rollupOptions: {
output: {
chunkFileNames: 'assets/js/[name]-[hash].js',
entryFileNames: 'assets/js/[name]-[hash].js',
assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
}
}
}
})
6、查看效果
npm run dev