一开始我的项目是没有babel.config.js的
只有vite.config.js
因为使用react,需要配置babel,编译jsx文件,索性就直接创建了一个babel,但是不知为什么就是配置不成功,有没有配置过的,有无好的解决方法,或者说,哪里配置的不对呢
vite.config.js
import { loadEnv } from "vite";
import { viteMockServe } from "vite-plugin-mock";
import { createVuePlugin } from "vite-plugin-vue2";
import { createSvgPlugin } from "vite-plugin-vue2-svg";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import path from "path";
//import react from "@vitejs/plugin-react";
import babel from "vite-plugin-babel";
const CWD = process.cwd();
export default ({ mode }) => {
const { VITE_BASE_URL } = loadEnv(mode, CWD);
return {
base: VITE_BASE_URL,
resolve: {
alias: {
"~": path.resolve(__dirname, "./"),
"@": path.resolve(__dirname, "./src")
}
},
css: {
preprocessorOptions: {
less: {
modifyVars: {}
}
}
},
plugins: [
createVuePlugin({
jsx: true
}),
react(
{
babel: {
// presets: [],
// // Your plugins run before any built-in transform (eg: Fast Refresh)
// plugins: [],
// // Use .babelrc files
// babelrc: true,
// Use babel.config.js files
// configFile: path.resolve(__dirname, "babel.config.js")
plugins: ["@babel/plugin-transform-react-jsx"]
}
}
),
babel(),
viteMockServe({
mockPath: "mock",
localEnabled: true
}),
createSvgPlugin(),
// svg 图标
createSvgIconsPlugin({
iconDirs: [path.resolve(CWD, "src/assets/icons/svg")], // svg存放路径
symbolId: "icon-[dir]-[name]"
})
],
babel.config.js
const path = require("path");
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = {
compact: false,
presets: [
"@vue/cli-plugin-babel/preset"
],
env: {
development: {
// babel-plugin-dynamic-import-node plugin only does one thing by converting all import() to require().
// This plugin can significantly increase the speed of hot updates, when you have a large number of pages.
plugins: [
"dynamic-import-node",
"@babel/plugin-proposal-optional-chaining"
]
}
},
// 使用overrides是为了分开配置jsx的解析规则,在react_app里使用react的规则解析,其他使用vue的规则
overrides: [
{
// 这里如果不用函数,会出现报错的情况,还没找到原因
// babel会提示Configuration contains string/RegExp pattern, but no filename was passed to Babel
// 因为filename不存在,如果不存在就必须通过回调返回一个undefined
test: function(filename) {
// 仅对src/react_app目录有效
if (filename !== undefined && filename.indexOf(resolve("src/react_app")) === 0) return filename;
},
plugins: ["@babel/plugin-transform-react-jsx"],
presets: [
["@vue/cli-plugin-babel/preset", {
// 关闭vue的jsx编译
jsx: false
}],
"@babel/preset-react" // 添加 React 的 preset
]
}
]
};