實(shí)現(xiàn)邏輯
1. 獲取到所有的測(cè)試腳本文件 *.spec.js
- 借助 glob 庫(kù)
import glob from 'glob'
const files = glob.sync("*.spec.js")
console.log(files, 'ffff')
2.得到每個(gè)文件里的內(nèi)容
import fs from 'fs/promises'
const fileContent = await fs.readFile("first.spec.js", "utf-8")
console.log(fileContent)
3.執(zhí)行文件里的內(nèi)容
new Function(fileContent)()
報(bào)錯(cuò):SyntaxError: Cannot use import statement outside a module
at new Function (<anonymous>)
因?yàn)槲覀兾募镉?Import 而 import 不能包裹在函數(shù)內(nèi)執(zhí)行
- 解決方式:使用打包器
安裝 esbuild
import { build} from 'esbuild'
await runModule(fileContent)
async function runModule(fileContent) {
const result = await build({
stdin: {
contents: fileContent,
resolveDir: process.cwd(),
},
// 不寫入文件
write: false,
// 將文件都打包到一個(gè)文件里
bundle: true,
target: "esnext"
})
new Function(result.outputFiles[0].text)()
}
4. 遍歷文件
for(const file of files) {
const fileContent = await fs.readFile(file, "utf-8")
await runModule(fileContent)
}
5. 不使用run
for(const file of files) {
const fileContent = await fs.readFile(file, "utf-8")
await runModule(fileContent + ";import {run} from './core.js'; run()")
}