feat: add 动态执行模块
This commit is contained in:
@@ -1,3 +1,10 @@
|
||||
import path from 'path';
|
||||
export const getRequire = () => {
|
||||
return eval('require') as NodeRequire;
|
||||
};
|
||||
|
||||
export const directoryPath = path.resolve(__dirname);
|
||||
|
||||
export const defaultImportModules = [
|
||||
{
|
||||
name: 'sequelize',
|
||||
@@ -8,3 +15,20 @@ export const defaultImportModules = [
|
||||
version: '^8.12.1',
|
||||
},
|
||||
];
|
||||
|
||||
export const dynamicImport = async (name: string) => {
|
||||
// const nodeModules = path.resolve(directoryPath, 'node_modules');
|
||||
// const nodeName = path.resolve(nodeModules, name);
|
||||
const require = getRequire();
|
||||
console.log(`Dynamic import module ${name}`);
|
||||
try {
|
||||
const nodeCache = require.cache[require.resolve(name)];
|
||||
if (nodeCache) {
|
||||
console.log(`${name} is cached`);
|
||||
}
|
||||
return require(name);
|
||||
} catch (e) {
|
||||
console.error(`Failed to import module ${name}: ${e.message}`);
|
||||
throw `Failed to import module ${name}: ${e.message}`;
|
||||
}
|
||||
};
|
||||
|
||||
46
src/lib/npm.ts
Normal file
46
src/lib/npm.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { exec } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
export const directoryPath = path.resolve(__dirname);
|
||||
const packagePath = path.resolve(directoryPath, 'package.json');
|
||||
const exists = (filePath: string) => {
|
||||
try {
|
||||
fs.accessSync(filePath);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const installPackage = async (packageName: string) => {
|
||||
if (!exists(packagePath)) {
|
||||
fs.writeFileSync(packagePath, JSON.stringify({ name: 'npm-install', version: '1.0.0' }), 'utf-8');
|
||||
}
|
||||
return await new Promise((resolve, reject) => {
|
||||
console.log(`Starting installation of ${packageName}...`);
|
||||
// 在程序运行路径下执行 npm install 命令
|
||||
console.log(`npm install ${packageName}`);
|
||||
|
||||
exec(`npm install ${packageName}`, { cwd: directoryPath }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.error(`Error installing package: ${stderr}`);
|
||||
reject(new Error(`Failed to install package ${packageName}`));
|
||||
} else {
|
||||
console.log(`Package ${packageName} installed successfully: ${stdout}`);
|
||||
resolve(stdout);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
export const getPackage = async () => {
|
||||
if (!exists(packagePath)) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
|
||||
} catch (e) {
|
||||
console.error('Failed to read package.json');
|
||||
return {};
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user