vite项目初始化之~按需引入Element-plus

998 阅读1分钟

插件推荐: xuwu(虚无)模板助手

介绍

本文介绍的是xuwu模版助手中的 ElementUi 这个模块相关代码,还会陆续更新相关的其他功能,比如ajax请求模版,生产环境去掉console,eslint+commit代码时统一风格,移动端consoleLog控制台,移动端适配,ElementUi,VantUi,AntDesignUi的按需引入等。

依赖安装

依赖包括两部分,Element解析样式的需要使用sasssass-loader,按需引入插件vite-plugin-style-import

"devDependencies": {
    "sass": "^1.32.13",
    "sass-loader": "^10.2.0",
    "vite-plugin-style-import": "^1.4.0",
    "element-plus": "^1.2.0-beta.5"
}

修改vite.config.js 文件

因各个Ui组件库结构不同,需要根据不同的组件库设置不同的解析文件和路径。
1、设置要使用的是什么模块
2、样式路径寻找

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import';


export default defineConfig(({ mode, command }) => ({
  plugins: [
    vue(),
    styleImport({ 
      libs: [ { 
        libraryName: "element-plus", 
        esModule: true,  
        resolveStyle: (name) => `element-plus/es/components/${name.replace("el-","")}/style/index`
      }
    ]
  })],
}))

配置按需引入文件

为了简化入口文件,将整个文件进行抽离,同时将这两个组件整合成一个整体,方便vue加载

//src/plugins/element.js
import {
  ElAlert,
  ElButton
} from 'element-plus'
const components = [
  ElAlert,
  ElButton
]
const install = (app) => {
  components.forEach((component) => {
    app.component(component.name, component)
  })
}
export default {
  install
}

在mian.js文件中引入按需引入的文件

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

import element from './plugins/element'
app.use(element)

app.mount('#app')

启动页面

页面可以正常显示出测试按钮 image.png

注意:

如果element-plus使用按需引入一定要注意使用的element版本。我最开始使用的是^1.0.2-beta.46整个包结构约等于vue2的包结构,路径需要做一定的调整。