@modern-js/create 2.69.5 → 3.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/run.js CHANGED
@@ -1,12 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
2
6
 
3
- const fs = require('fs');
4
- const path = require('path');
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+ const require = createRequire(import.meta.url);
5
10
 
6
11
  const pkgInfo = require(path.join(__dirname, '../package.json'));
7
12
  const srcPath = pkgInfo['jsnext:source'];
8
13
  const distPath = pkgInfo.main;
9
14
  const project = path.join(__dirname, '../tsconfig.json');
15
+
10
16
  let env = 'production';
11
17
  if (fs.existsSync(project)) {
12
18
  env = 'development';
@@ -15,12 +21,53 @@ if (process.env.CODESMITH_ENV) {
15
21
  env = process.env.CODESMITH_ENV;
16
22
  }
17
23
 
24
+ const entry = path.join(
25
+ __dirname,
26
+ `../${env === 'development' ? srcPath : distPath}`,
27
+ );
28
+
18
29
  if (env === 'development') {
19
- require('ts-node').register({ project });
20
- }
30
+ try {
31
+ // 从当前包的 node_modules 中解析 tsx/esm/api
32
+ // 使用 require.resolve 来找到 tsx 包的位置
33
+ const packageRoot = path.join(__dirname, '..');
34
+ let tsxApiPath = 'tsx/esm/api';
35
+
36
+ try {
37
+ // 尝试解析 tsx 包的 package.json
38
+ const tsxPackageJson = require.resolve('tsx/package.json', {
39
+ paths: [packageRoot],
40
+ });
41
+ const tsxPackageDir = path.dirname(tsxPackageJson);
42
+ // 根据 tsx 的 exports 配置,esm/api 指向 dist/esm/api/index.mjs
43
+ const tsxApiFile = path.join(
44
+ tsxPackageDir,
45
+ 'dist',
46
+ 'esm',
47
+ 'api',
48
+ 'index.mjs',
49
+ );
50
+ if (fs.existsSync(tsxApiFile)) {
51
+ tsxApiPath = pathToFileURL(tsxApiFile).href;
52
+ }
53
+ } catch {
54
+ // 如果解析失败,使用默认的模块名(Node.js 会从工作区的 node_modules 中查找)
55
+ }
21
56
 
22
- try {
23
- require(`../${env === 'development' ? srcPath : distPath}`).default();
24
- } catch (e) {
25
- console.error(e);
57
+ const { register } = await import(tsxApiPath);
58
+ register({
59
+ tsconfig: project,
60
+ });
61
+ await import(pathToFileURL(entry).href);
62
+ } catch (error) {
63
+ console.error('Error: Cannot load TypeScript file in development mode.');
64
+ console.error('Please install tsx: pnpm add -D tsx');
65
+ console.error('Or build the project: pnpm build');
66
+ console.error(error);
67
+ process.exit(1);
68
+ }
69
+ } else {
70
+ import(pathToFileURL(entry).href).catch(e => {
71
+ console.error(e);
72
+ });
26
73
  }