Vue 2 中,使用Vite作为前端构建开发工具,替代webpack(二)常见问题——和webpack 入口文件同名冲突 & 将commonjs转化为es module-cjs2esmodule

常用问题【踩坑】
1、 vite 目前要求入口文件必须是根目录下的 index.html,如果之前的 webpack 入口文件同名,需要更改。

解决方案:vite.config.js:

import { injectHtml } from 'vite-plugin-html';
export default defineConfig({
  plugins:[
    injectHtml({ // 入口文件 index.html 的模板注入
      injectData: { // 模板注入的数据
        htmlWebpackPlugin: { // 取和 webpack 插件同名的对象 key,即可
          options: {
            isVite: true,
            shotcut: '/static/img/favicon.png',
          }
        },
        title: 'HMO 运营后台'
      },
    })
  ]
})

webpack.xxx.js

new HtmlWebpackPlugin({
  template: 'index.html',
  inject: true,
  isVite: false // 添加标识
})

根目录入口文件 index.html - ejs 模板

<% if (htmlWebpackPlugin.options.isVite) { %>
<script type="module" src="/src/main.js"></script>
<%}%>
2、新版本报 xx 错:可切换旧版本,如 vite@2.2.3
3、没有导出命名?

在这里插入图片描述

# 未捕获的语法错误:请求的模块“/config/index”。js'不提供名为'default'的导出未捕获语法错误:请求的模块'/config/index'。js'不提供名为'default'的导出

Uncaught SyntaxError: The requested module '/config/index.js' does not provide an export named 'default'Uncaught SyntaxError: The requested module '/config/index.js' does not provide an export named 'default'

cjs2esmodule地址——https://www.npmjs.com/package/cjs2esmodule

错误原因:浏览器仅支持 esm,不支持 cjs vite.config.js

import { cjs2esmVitePlugin } from 'cjs2esmodule'
export default defineConfig({
  plugins: [
   cjs2esmVitePlugin(), // 将 commonjs 转化为 es module
  ]
})

如果有 require.xx 的按需加载写法还可以修改成 import 的,案例如下:

const subjectList = r => require.ensure( [], () => r(require('@/pages/xxx/subject/list.vue')), 'subject' );
 
// 改为:Vue 动态组件 component: ()=>import()
 
const subjectList = () => import(/* webpackChunkName: "subject" */ '@/pages/xxx/subject/list.vue')
const arr = [
  {
    path: '/subject/list',
    name: 'subject/list',
    component: subjectList
    meta: {...}
  }
];
export default arr;
4、 proxy 使用 http-proxy。

案例:

proxy: {
    '/rest': {
        target: 'http://my.web.com/',
        changeOrigin: true,
        bypass: (req, res, proxyOption) => {
           console.log(`当前请求代理:${req.url} -> ${proxyOption.target}`);
        },
    },
}
5、ts 文件报错?

验证是否配置了 vite 的 ts 处理

"compilerOptions": {
  "types": ["vite/client"]
}
6、全局环境变量报错?
// const isProd = ENV === 'production'; // webpack - dev 环境变量
// const isProd = import.meta.env.PROD; // vite - dev 环境变量
// 可以避开上面????????的,采用 NODE_ENV 来区分:
const isProd = process.env.NODE_ENV === 'production';
 
那么我们启动的时候:"dev": "NODE_ENV=development vite"

或参考社区的 babel 插件:babel-preset-vite

【包含以下两个功能】

  • babel-plugin-transform-vite-meta-env

  • babel-plugin-transform-vite-meta-glob

7、看一些打印出来的日志&错误等?

cli --debug,或者 vite.config.js 配置打印相关参数

8、引入文件,比如.vue 的时候,不可以省略扩展名?

不可以,设计如此。加上 resolve.extensions: [‘.vue’] 直接在控制台报错

# 错误:没有为“.vue”配置加载程序
error: No loader is configured for ".vue"
9、less 文件找不到?
# [vite]内部服务器错误:“~@/styles/var.less”未找到。
[vite] Internal server error: '~@/styles/var.less' wasn't found.

(1)确定已经支持 less:npm install -D less

(2)别忘了 resolve.alias 也加上一个:'~@': resolve('src')

10、如何支持 jsx?

vite.config.js

import { createVuePlugin } from 'vite-plugin-vue2';
createVuePlugin({
  jsx: true, // 配置 jsx
  jsxOptions: {
    injectH: false,
  },
})

index.vue

Vue.component('my-component',{
 render () {
   return (<div>my template</div>)
  }
})
11. 根据环境变量配置代理?
(1)cross-env 来跨平台设置环境变量
# 安装 cross-env
npm i cross-env -D
(2)加载环境变量文件。

它能将环境变量中的变量从 .env 文件加载到 process.env 中

# 安装 dotenv
npm i dotenv -D
(3)config/.env.development 配置变量
NODE_ENV = development
API_LOCATION = /api
LOGOUT_PC_LOCATION = http://user.myweb.com/login
CRM_ADDRESS = http://crm.myweb.com
(4)配置 vite.config.ts
try {
  // 根据环境变量加载环境变量文件
  const file = dotenv.parse(fs.readFileSync(`./config/.env.${process.env.NODE_ENV}`), {
    debug: true
  })
  console.log(file)
  // 根据获取的 key 给对应的环境变量赋值
  for (const key in file) {
    process.env[key] = file[key]
  }
} catch (e) {
  console.error(e)
}
const API_LOCATION = process.env.API_LOCATION || '/api'
..... 此处省略
 
export default defineConfig({
  server: {
    proxy: {
      [API_LOCATION]: {
        target: 'http://127.0.0.1:8001',
        rewrite: (path) => path.replace(API_LOCATION, '') // 根据环境变量配置代理
      }
 
    }
  }
})
(5)package.json 启动 script
"vite": "cross-env NODE_ENV=development vite"
12、环境变量报错?

原来 webpack 使用的环境变量 process.env,vite 没有这个,所以报错

# 未捕获引用错误:未定义进程
Uncaught ReferenceError: process is not defined

vite 使用的时候import.meta.env, 但是我们老的代码不想动怎么办?

其实 vite 也还是留了口子给我们定义全局变量(类型不能是 function)

export default defineConfig({
  // ...
  define: {
    'process.env': {}
  }
})
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐