vite vue使用pont-engine

发布时间 2023-04-18 12:14:34作者: 丁少华

pont-engine

是一款阿里的api生成工具

安装依赖即可

yarn add --dev pont-engine

然后即可使用

pont start

问题

但是因为默认生成的代码 包含cjs的模块语法,所以vite无法识别。
另外生成代码前最好把旧的生成目录删除!

解决办法

因此我做了如下优化,让您一键执行这些操作 并生成适应vite的代码:
在项目根目录下创建脚本命令 shell\gen-api.js

const shell = require('shelljs');
const child_process = require('node:child_process');

// 移除旧的services目录
shell.rm('-rf', 'src/services');
// 执行生成api目录(shell目前不支持exec需要交互式输入的运行命令,所以只能用原生 https://github.com/shelljs/shelljs/wiki/FAQ#running-interactive-programs-with-exec)
child_process.execSync('pont start',{stdio: 'inherit'});
// 替换生成文件里vite不支持的语法
const pontCorePath = './src/services/pontCore.js';
shell.sed('-i', 'Object.defineProperty.*', '', pontCorePath);
shell.sed('-i', 'exports.PontCore = void 0;', '', pontCorePath);
shell.sed('-i', 'exports.PontCore', 'export const PontCore', pontCorePath);

pa中添加一键打包命令

"scripts": {
  "pont": "node ./shell/gen-api.js",
   ...
},

注意 脚本依赖一个三方包 shelljs,记得安装一下

yarn add shelljs

使用

npm run pont