首页 > 其他分享 >Vue2 项目中添加 vite

Vue2 项目中添加 vite

时间:2023-02-20 15:59:02浏览次数:47  
标签:index Vue2 plugin html 添加 vue2 组件 vite

正常创建Vue2项目

使用命令方式

vue create projectname

使用图形方式

vue ui

安装 vite 相关组件

安装组件,此组件是开发依赖包

npm install vite vite-plugin-vue2 vite-plugin-html --save-dev
组件 说明
vite 核心组件
vite-plugin-vue2 vue2 vite 配置
vite-plugin-html html 相关配置,用于index.html中配置信息

文件操作

1、将 public/index.html,移动到项目根下面,在根下面新建 vite.config.js 文件。

2、编辑 vite.config.js,加入以下代码

import { defineConfig } from "vite"
import { createVuePlugin } from "vite-plugin-vue2"
import { createHtmlPlugin } from "vite-plugin-html"

export default defineConfig({
  plugins: [
    createVuePlugin(),
    createHtmlPlugin({
      // 入口文件:这里配置,就不需要在index.html中加入script标签来引入
      entry: "src/main.js",
      // 首页文件,如果要放到其它地方需配置它的路径,否则不需要配置。默认:/index.html
      template: "index.html",
      // 需要注入 index.html ejs 模板的数据
      inject: {
        data: {
          // index.html  <link rel="icon" href="<%= BASE_URL %>favicon.ico">中的变量值
          BASE_URL: "/",
          // index.html <%= htmlWebpackPlugin.options.title %>中的变量值
          htmlWebpackPlugin: {
            options: {
              title: "vue2 使用 vite"
            }
          },
          // 自定义变量值,可以代替<%= htmlWebpackPlugin.options.title %>为<%= title %>
          title: "vue2 使用 vite"
        }
      }
    })
  ],
  resolve: {
    alias: [
      // 路径中 @对的对应关系
      {
        find: "@",
        replacement: "/src"
      }
    ]
  }
})

3、注意 index.html 中的 <%= 变量%>,它中的变量一定要配置,不然运行要出错!这个坑很坑!!!

4、编辑 package.json,修改 scripts项,加入 vite 启动方式

运行界面

按 h 键显示 2中的快捷键。按 o 键 在默认浏览器 打开 程序,按 q 键 退出程序。
之后大家就可以感受 vue2 中编译和运行的流畅了!关于 vite 的发布(build),自行查询吧。

标签:index,Vue2,plugin,html,添加,vue2,组件,vite
From: https://www.cnblogs.com/LaughM/p/17137687.html

相关文章