@vue/cli 5.x 搭建vue3项目,集成ant design vue 3.x, 实现自动按需引入, 并整合 tailwindcss

447 阅读1分钟

包管理工具

yarn 1.22.22

先用vue-cli创建基本的vue3项目

vue create webpack-vue3-01

安装依赖,再升级vue版本

yarn install
yarn upgrade vue --latest

查看当前项目vue版本: yarn list vue

安装 ant design vue,以及配置按需引入

yarn add @ant-design/icons-vue ant-design-vue

yarn add unplugin-auto-import unplugin-vue-components babel-plugin-import less less-loader -D

yarn add speed-measure-webpack-plugin -D

unplugin-auto-import unplugin-vue-components: 实现普通组件自动按需引入

babel-plugin-import: 实现antd vue的message组件的样式自动引入

less less-loader: 引用less

speed-measure-webpack-plugin: 记录webpack编译,打包速度,并输出到终端

vue.config.js

const { defineConfig } = require('@vue/cli-service')
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { AntDesignVueResolver } = require('unplugin-vue-components/resolvers')
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");

const isDev = process.env.NODE_ENV == 'development'

const antdvResolverConfig = {
  importStyle: 'less',
}
module.exports = defineConfig({
  transpileDependencies: true,
  chainWebpack:(config)=>{
    config.plugin('speed-measure-webpack-plugin').use(SpeedMeasurePlugin).end();

    config.plugin('define').tap((definitions) => {
      Object.assign(definitions[0], {
        __VUE_OPTIONS_API__: 'true',
        __VUE_PROD_DEVTOOLS__: 'false',
        __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
      })
      return definitions
    })

    config.plugin('speed-measure-webpack-plugin').use(SpeedMeasurePlugin).end();
  },
  configureWebpack:(config)=>{

    config.plugins.push(AutoImport.default({
      resolvers: [AntDesignVueResolver(antdvResolverConfig)]
    }))
    config.plugins.push(Components.default({
      resolvers: [AntDesignVueResolver(antdvResolverConfig)]
    }))

    // 通过文件缓存,加快二次启动速度
    config.cache={
      type:'filesystem'
    }
  },
  css:{
    loaderOptions:{
      less:{
        lessOptions: {
          javascriptEnabled: true
        } 
      }
    }
  },
  devServer:{
    host: "localhost", // 启动服务器域名
    port: "3000", // 启动服务器端口号
    open: true, // 是否自动打开浏览器
    hot: true, // 开启HMR功能(只能用于开发环境,生产环境不需要了)
  }
})

babel.config.js

module.exports = {
  compact: false,
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  plugins: [
    [
      "import",
      { libraryName: "ant-design-vue", libraryDirectory: "es", style: true },
    ], // `style: true` 会加载 less 文件
  ]
}

整合tailwindcss

yarn add tailwindcss postcss autoprefixer -D

postcss.config.js

module.exports = {
    plugins:{
        tailwindcss: {},
        autoprefixer: {},
    }
}

src\assets\css\index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

main.js

import './assets/css/index.css'
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

源码

free pan/webpack-vue3-01 (gitee.com)