如何在vite中使用babel插件

8,541 阅读1分钟

概括

做vite搭建的项目时候,有时候可能想利用下babel插件来处理下你写的js代码。

  1. 比如我想利用自定义的tryCatch的babel插件,来简化写js的繁琐。
  2. 比如在使用vue3.2和vite4.0+开发一个移动端H5,测试时发现低版本的浏览器出现白屏的现象,原因是很多低版本浏览器并不支持原生ESM导入的方式,这就需要使用 babel 插件将 ECMAScript 2015+ 代码转换为 JavaScript 向后兼容版本的代码

如何在vite中使用babel插件呢? 可以借助vite-plugin-babel

使用方式

viteConfig.js

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import babel from "vite-plugin-babel";

export default defineConfig({
    plugins: [
        babel(),
        vue(),
    ],
    build: { target: 'es2015' } //为支持不支持es6的服务,
});

babel.config.js

const devDebug = require("./babelPlugin/devDebug.js");

module.exports = {
    plugins: [devDebug],
};

devDebug.js

const t = require("@babel/types");

module.exports = () => {
    return {
        visitor: {
            Identifier: (path, state) => {
                const nodeName = path.node.name;
                const isDebug = nodeName === "DEBUG";

                const parentPath = path.parentPath;
                const parentIsIf = t.isIfStatement(parentPath);

                if (isDebug && parentIsIf) {
                    const stringNode = t.stringLiteral("DEBUG");
                    path.replaceWith(stringNode);
                }
            },
            Literal: (path, state) => {
                const nodeVal = path.node.value;
                const isDebug = nodeVal === "DEBUG";
                const parentPath = path.parentPath;
                const parentIsIf = t.isIfStatement(parentPath);

                if (isDebug && parentIsIf) {
                    const isPro = process.env.NODE_ENV;
                    if(isPro) {
                        path.parentPath.remove();
                    }
                }
            },
        },
    };
};

可参看astexplorer.net/ 去设置相关的节点类型的处理

参看文章如下:

1, babel - path常用方法总结

2, babel - path常用属性总结

3, AST介绍和babel插件开发

4, Babylon - babel中使用的 JavaScript 解析器