[vue] Vite的使用

之前一直使用的是@vue/cli脚手架,创建新的项目,但是现在该脚手架已经处于维护阶段了,而且官网也推荐使用vite,所以这里记录一下对已有项目的迁移 @vue/cli 迁移成 vite

环境

 "vue": "^3.2.47",
 "vite": "^4.1.4",

package.json文件变更

变更脚手架

1.删除原有脚手架相关包,新增脚手架

npm uninstall @vue/cli-service
npm i vite @vitejs/plugin-vue

2.移除babel?
但是按需引入等功能?

修改脚本命令

 "serve": "vue-cli-service serve",
 "build": "vue-cli-service build",
 "lint": "vue-cli-service lint",
"serve": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",

--fix用于自动修复可忽略

index.html 文件

htmlWebpackPlugin 替换为 vite-plugin-html

提示无法使用 htmlWebpackPlugin 插件 ,替换成vite-plugin-html插件

npm uninstall html-webpack-plugin
npm i vite-plugin-html -D

所有关于该插件的使用都需要替换,可以暂时先注释,方便程序的启动

index.html 文件在@vue/cli下是放在根目录的public文件夹中的,但是迁移文档说是改成vite则需要放在根目录下

然后,不使用vite-plugin-html插件的时候没有任何问题,但是发现在启用vite-plugin-html插件时,也即在vite.config.ts中配置该插件时总是报错,并且加载的是public中的index.html文件

所以又将index.html 文件移回了public文件夹中,此时正常启动,vite.config.ts的配置

import { createHtmlPlugin } from "vite-plugin-html";
export default defineConfig(({ command, mode, ssrBuild }) => {

  return {
    plugins: [
      createHtmlPlugin({
        inject: {
          data: {
            title: "Vue3.x",
            online: `${online}`
          }
        }
      }),
    ]
  }

index.html中的使用

<strong>We're sorry but <%= title %> doesn't work properly without JavaScript enabled.Please enable it to continue.</strong>

We’re sorry but vue3.x-vite-ts doesn’t work properly without JavaScript enabled. Please enable it to continue.

运行时报了以上错误

<script type="module" src="/src/main.ts"></script>

迁移文档中有说明,vite 不在自动注入,但是迁移时被忽略了,因此导致了该问题,添加上述代码后正常

vite.config.ts 文件变更

该文件中的变更本人是根据运行时错误提示与需求不断添加的,如果再次迁移可以直接添加,错误可以等报错的时候在添加相应配置

vite-plugin-html

该插件的使用可查看 htmlWebpackPlugin 替换为 vite-plugin-html 一节

You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.

在vite.config.ts中添加:

resolve: {
  alias: {
    'vue-i18n': "vue-i18n/dist/vue-i18n.esm-browser.js"
  }
}

[vite] Internal server error: [less] Inline JavaScript is not enabled. Is it set in your options?

在vite.config.ts中添加less的配置

   {
     css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true
        }
      }
    }
   }

移除console

@vue/cli的console去除方式

babel.config.js

const prodPlugin = []

if (process.env.NODE_ENV === 'production') {
  // 如果是生产环境,则自动清理掉打印的日志,但保留error 与 warn
  prodPlugin.push([
    'transform-remove-console',
    { // 不清理的内容console
      exclude: ['error', 'warn'] 
    }
  ])
}
module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"],
  plugins: [
    [// 按需加载js
      "import",
      {libraryName: "ant-design-vue", libraryDirectory: "es", style: true}
    ],
    ...prodPlugin
  ]
};

vite的console去除方式

npm uninstall core-js
npm uninstall babel-plugin-import
npm uninstall babel-plugin-transform-remove-console

vite.config.js中添加配置

{
  build:{
    terserOptions: {
        compress: {
          //生产环境时移除console
          drop_console: true,
          drop_debugger: true
        }
      },
    esbuild: {//移除方式2
      drop: mode === 'production' ? ['console', 'debugger'] : []
    },

  }
}

配置运行的时候自动检测eslint规范

npm i vite-plugin-eslint

vite.config.ts添加配置

plugins: [
  eslintPlugin({
    include: ["src/**/*.ts", "src/**/*.vue"]
  })
]

项目中文件的变更

i18n.ts:139 ReferenceError: require is not defined

Vite默认使用es6标准的 import 的导入方式,不支持require引入。默认有Vite自己的引入方式

静态资源的引入还比较好解决,可以使用new URL(),但是文件批量引入时的问题有效的解决方案:

@vue/cli 的 webpack 批量文件引入方案

const folderRequireContext: __WebpackModuleApi.RequireContext =
      require.context(
        "../router",
        true,
        /[/\\]route[/\\]([a-z]{2})_?([A-Z]{2})?\.ts$/
      );

vite 批量文件引入方案

懒加载方式,使用的时候才加载:

const fileRequireContext = import.meta.glob("../router/*.ts");
fileRequireContext[fileFullName]().then((content: any) => {
  console.log(content.default)
})

直接加载方式:

const fileRequireContext = import.meta.globEager("../router/*.ts");
Object.keys(fileRequireContext).forEach((fileFullName) => {
  const content=fileRequireContext[fileFullName];
})

因为import.meta无法使用表达式,所以看了一下其它匹配的方式:

  • ../router/router*.ts:所有以router开头的ts文件

  • /**/:表示嵌套的多层文件夹

ImportMeta上不存在属性 "glob" 的错误

vscode使用import.meta.glob时,报以上错误,在tsconfig.json文件中添加配置

{
  "compilerOptions": {
    "types": [
      "vite/client"
    ],
  },
}

环境变量的使用

@vue/cli获取环境变量的方式

process.env.NODE_ENV

vite获取环境变量的方式

import.meta.env.PROD

Uncaught RangeError: Maximum call stack size exceeded

路由的默认配置问题,发现这个问题主要是因为路由配置的跳转什么的出现了问题,本人是因为框架路由跳转子路由时导致的该问题:

router.push("/dashboard")//菜单栏框架
router.push("/about")//内容区展示的路由

因为上述问题导致的, about 是 dashboard 的子路由,所以删除子路由about的跳转后,该问题消失,但是如何在跳转到子路由,在路由 dashboard 的子路由添加默认子路由跳转:

{
    path: "/",
    redirect: "/about",//设置home路径的默认展示页面
  }

还有注意一下,路由是不是正确配置了,在实践过程中还有一个情况会导致该问题,是因为import.meta批量文件懒加载导致路由数组为空,因为404路由都没有,所以导致上述问题!!!

eslint配置问题

之前都是默认生成eslint问题,但是在vite中需要自己配置

@vue/cli中配置文件.eslintrc.js

module.exports = {
  root: true,
  env: {
    es2021: true
  },
  extends: [
    "eslint:recommended",
    "plugin:vue/vue3-essential",
    "@vue/typescript/recommended",
    "@vue/prettier",
    "plugin:prettier/recommended"
  ],
  // parserOptions: {
  //   ecmaVersion: 2020 rome
  // },
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
    "prettier/prettier": "off",
    // "@typescript-eslint/explicit-module-boundary-types": "off",
    "@typescript-eslint/no-explicit-any": "off",
    // "@typescript-eslint/no-array-constructor":"off",
    "@typescript-eslint/no-empty-function": "warn",
    "@typescript-eslint/no-unused-vars": "off",
    "@typescript-eslint/no-unused-requires": "off",
    // "@typescript-eslint/ban-types": "off",
    // "vue/no-unused-components":"off",
    "vue/multi-word-component-names": "off", //vue文件命名
    // "no-array-constructor": "off",
    // "no-irregular-whitespace": "off",
    "vue/no-unused-vars": "off",
    // 'prefer-const': 'off',
    "linebreak-style": [0, "error", "windows"]
  },
  overrides: [
    {
      files: [
        "**/__tests__/*.{j,t}s?(x)",
        "**/tests/unit/**/*.spec.{j,t}s?(x)"
      ],
      env: {
        jest: true
      }
    }
  ]
};

vite中配置.eslintrc.js

npm i eslint
npx eslint --init

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pYKWbChR-1677746180611)(2023-03-01-10-53-28.png)]

.eslintrc.js配置文件

生成的默认配置文件

module.exports = {
    "env": {
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/vue3-essential",
        "plugin:@typescript-eslint/recommended"
    ],
    "overrides": [
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    "rules": {
    }
}

添加 prettier

prettier已经初始化过

extends中添加

//初始化插件
npm i eslint-config-prettier
//添加配置
{
  extends: [
    "eslint:recommended",
    // "plugin:vue/vue3-recommended",
    "plugin:vue/vue3-essential",
    "plugin:@typescript-eslint/recommended",
    "eslint-config-prettier",
    "plugin:prettier/recommended"
  ]
}

缩进问题与空格问题

有些页面上显示的是箭头缩进,有些是空格的缩进方式,发现使用替换根本不管用,保存后又变成了箭头
在这里插入图片描述
点击下述内容变更
在这里插入图片描述
弹出
在这里插入图片描述
转换成功
在这里插入图片描述

主题设置

该主题设置暂时没有好的设计方案,之前webpack的已经不可用,等之后有了解决方案在记录

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三知之灵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值