@modern-js/module-tools 2.37.1 → 2.38.0-beta.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.
@@ -74,11 +74,16 @@ const runBuildTask = async (options, api) => {
74
74
  const generatorDts = async (config, api, options) => {
75
75
  const { runRollup, runTsc } = await Promise.resolve().then(() => __toESM(require("./dts")));
76
76
  const { watch, dts } = options;
77
- const { buildType, input, sourceDir, alias, externals, tsconfig, footer: { dts: footer }, banner: { dts: banner } } = config;
77
+ const { buildType, input, sourceDir, alias, externals, tsconfig, footer: { dts: footer }, banner: { dts: banner }, format, autoExtension } = config;
78
78
  const { appDirectory } = api.useAppContext();
79
79
  const { distPath, abortOnError, respectExternal } = dts;
80
80
  var _dts_tsconfigPath;
81
81
  const tsconfigPath = (_dts_tsconfigPath = dts.tsconfigPath) !== null && _dts_tsconfigPath !== void 0 ? _dts_tsconfigPath : tsconfig;
82
+ const { dtsExtension } = (0, import_utils2.getDefaultOutExtension)({
83
+ format,
84
+ root: appDirectory,
85
+ autoExtension
86
+ });
82
87
  const generatorDtsConfig = {
83
88
  distPath,
84
89
  watch,
@@ -91,7 +96,8 @@ const generatorDts = async (config, api, options) => {
91
96
  footer,
92
97
  banner,
93
98
  alias,
94
- sourceDir
99
+ sourceDir,
100
+ dtsExtension
95
101
  };
96
102
  const prevTime = Date.now();
97
103
  (0, import_debug.debug)(`${(0, import_debug.label)("dts")} Build Start`);
@@ -11,5 +11,6 @@ export declare const runRollup: (api: PluginAPI<ModuleTools>, {
11
11
  respectExternal,
12
12
  appDirectory,
13
13
  footer,
14
- banner
14
+ banner,
15
+ dtsExtension
15
16
  }: GeneratorDtsConfig) => Promise<RollupWatcher | import("../../../compiled/rollup").RollupBuild | null>;
@@ -37,7 +37,7 @@ var import_typescript = __toESM(require("typescript"));
37
37
  var import_plugin_json = __toESM(require("../../../compiled/@rollup/plugin-json"));
38
38
  var import_rollup_plugin_dts = __toESM(require("../../../compiled/rollup-plugin-dts"));
39
39
  var import_utils2 = require("../../utils");
40
- const runRollup = async (api, { distPath, tsconfigPath, externals, input, watch, abortOnError, respectExternal, appDirectory, footer, banner }) => {
40
+ const runRollup = async (api, { distPath, tsconfigPath, externals, input, watch, abortOnError, respectExternal, appDirectory, footer, banner, dtsExtension }) => {
41
41
  const ignoreFiles = {
42
42
  name: "ignore-files",
43
43
  load(id) {
@@ -100,7 +100,8 @@ const runRollup = async (api, { distPath, tsconfigPath, externals, input, watch,
100
100
  format: "esm",
101
101
  exports: "named",
102
102
  footer,
103
- banner
103
+ banner,
104
+ entryFileNames: `[name]${dtsExtension}`
104
105
  };
105
106
  if (watch) {
106
107
  const { watch: watch2 } = await Promise.resolve().then(() => __toESM(require("../../../compiled/rollup")));
@@ -155,7 +155,7 @@ const adapterPlugin = (compiler) => {
155
155
  const dir = (_args_resolveDir = args.resolveDir) !== null && _args_resolveDir !== void 0 ? _args_resolveDir : args.importer ? (0, import_path.dirname)(args.importer) : root;
156
156
  const resultPath = isExternal ? args.path : getResultPath(originalFilePath, dir, args.kind);
157
157
  if (resultPath === false) {
158
- (0, import_debug.debugResolve)("empty resolve:", args);
158
+ (0, import_debug.debugResolve)("resolve false:", args);
159
159
  return {
160
160
  path: "/empty-stub",
161
161
  sideEffects: false
@@ -179,7 +179,7 @@ const adapterPlugin = (compiler) => {
179
179
  if (args.namespace === globalNamespace) {
180
180
  const value = config.umdGlobals[args.path];
181
181
  return {
182
- contents: `module.exports = (typeof globalThis !== "undefined" ? globalThis : Function('return this')() || global || self)[${JSON.stringify(value)}]`
182
+ contents: `module.exports = (typeof globalThis !== "undefined" ? globalThis : (typeof global !== "undefined" ? global : self || Function('return this')()))[${JSON.stringify(value)}]`
183
183
  };
184
184
  }
185
185
  if (args.suffix) {
@@ -33,6 +33,7 @@ __export(esbuild_exports, {
33
33
  });
34
34
  module.exports = __toCommonJS(esbuild_exports);
35
35
  var import_define_property = require("@swc/helpers/_/_define_property");
36
+ var import_path = __toESM(require("path"));
36
37
  var import_esbuild = require("esbuild");
37
38
  var tapable = __toESM(require("tapable"));
38
39
  var import_utils = require("@modern-js/utils");
@@ -66,10 +67,9 @@ class EsbuildCompiler {
66
67
  }
67
68
  }
68
69
  convertConfigToEsbuild(config) {
69
- const { input, buildType, define, target, sourceMap, platform, splitting, outDir, sourceDir, minify, jsx, esbuildOptions, format, asset, tsconfig, banner, footer } = config;
70
+ const { input, buildType, define, target, sourceMap, platform, splitting, outDir, sourceDir, minify, jsx, esbuildOptions, format, asset, tsconfig, banner, footer, shims, autoExtension } = config;
70
71
  const bundle = buildType === "bundle";
71
72
  const entryNames = bundle ? "[name]" : "[dir]/[name]";
72
- const absWorkingDir = this.context.root;
73
73
  let esbuildFormat = format === "umd" ? "esm" : format;
74
74
  if (bundle && format === "cjs" && splitting) {
75
75
  esbuildFormat = "esm";
@@ -82,7 +82,19 @@ class EsbuildCompiler {
82
82
  ".ts",
83
83
  ".json"
84
84
  ];
85
+ const { jsExtension } = (0, import_utils2.getDefaultOutExtension)({
86
+ format,
87
+ root: this.context.root,
88
+ autoExtension
89
+ });
85
90
  const buildOptions = {
91
+ inject: [
92
+ format === "cjs" && shims ? import_path.default.join(__dirname, "../../../shims/cjs.js") : "",
93
+ format === "esm" && shims && platform === "node" ? import_path.default.join(__dirname, "../../../shims/esm.js") : ""
94
+ ].filter(Boolean),
95
+ outExtension: autoExtension ? {
96
+ ".js": jsExtension
97
+ } : void 0,
86
98
  banner: import_utils.lodash.pick(banner, [
87
99
  "js",
88
100
  "css"
@@ -93,7 +105,12 @@ class EsbuildCompiler {
93
105
  ]),
94
106
  entryPoints: input,
95
107
  metafile: true,
96
- define,
108
+ define: {
109
+ ...format === "cjs" && shims ? {
110
+ "import.meta.url": "importMetaUrl"
111
+ } : {},
112
+ ...define
113
+ },
97
114
  bundle: buildType === "bundle",
98
115
  format: esbuildFormat,
99
116
  target: esbuildTarget,
@@ -102,7 +119,7 @@ class EsbuildCompiler {
102
119
  splitting,
103
120
  charset: "utf8",
104
121
  logLimit: 5,
105
- absWorkingDir,
122
+ absWorkingDir: this.context.root,
106
123
  platform,
107
124
  tsconfig: import_utils.fs.existsSync(tsconfig) ? tsconfig : void 0,
108
125
  write: false,
@@ -122,20 +139,20 @@ class EsbuildCompiler {
122
139
  };
123
140
  return esbuildOptions(buildOptions);
124
141
  }
125
- getTransformContext(path) {
126
- if (this.transformContextMap.has(path)) {
127
- return this.transformContextMap.get(path);
142
+ getTransformContext(path2) {
143
+ if (this.transformContextMap.has(path2)) {
144
+ return this.transformContextMap.get(path2);
128
145
  }
129
146
  const context2 = new import_transform.TransformContext(Boolean(this.context.config.sourceMap));
130
- this.transformContextMap.set(path, context2);
147
+ this.transformContextMap.set(path2, context2);
131
148
  return context2;
132
149
  }
133
- getSourcemapContext(path) {
134
- if (this.sourcemapContextMap.has(path)) {
135
- return this.sourcemapContextMap.get(path);
150
+ getSourcemapContext(path2) {
151
+ if (this.sourcemapContextMap.has(path2)) {
152
+ return this.sourcemapContextMap.get(path2);
136
153
  }
137
154
  const context2 = new import_sourcemap.SourcemapContext(Boolean(this.context.config.sourceMap));
138
- this.sourcemapContextMap.set(path, context2);
155
+ this.sourcemapContextMap.set(path2, context2);
139
156
  return context2;
140
157
  }
141
158
  emitAsset(name, chunk) {
@@ -40,7 +40,7 @@ var import_file = require("../../constants/file");
40
40
  var import_utils2 = require("../../utils");
41
41
  var import_asset = require("./asset");
42
42
  var import_postcssTransformer = require("./style/postcssTransformer");
43
- async function redirectImport(compiler, code, modules, aliasRecord, filePath, outputDir, matchPath) {
43
+ async function redirectImport(compiler, code, modules, aliasRecord, filePath, outputDir, jsExtension, matchPath) {
44
44
  const str = new import_magic_string.default(code);
45
45
  const extensions = [
46
46
  ".ts",
@@ -54,6 +54,7 @@ async function redirectImport(compiler, code, modules, aliasRecord, filePath, ou
54
54
  }
55
55
  const { start, end } = module2;
56
56
  let { name: name2 } = module2;
57
+ const ext = (0, import_path.extname)(name2);
57
58
  const { redirect: redirect2, asset } = compiler.config;
58
59
  const { alias, style } = redirect2;
59
60
  if (alias) {
@@ -75,8 +76,17 @@ async function redirectImport(compiler, code, modules, aliasRecord, filePath, ou
75
76
  name2 = relativeImportPath;
76
77
  }
77
78
  }
79
+ if (redirect2.autoExtension) {
80
+ if (ext === "" && jsExtension !== ".js" && name2.startsWith(".")) {
81
+ str.overwrite(start, end, `${name2}${jsExtension}`);
82
+ return;
83
+ }
84
+ if ((0, import_utils2.isTsExt)(name2)) {
85
+ str.overwrite(start, end, name2.replace(/\.(m|c)?tsx?$/, jsExtension));
86
+ return;
87
+ }
88
+ }
78
89
  if (style) {
79
- const ext = (0, import_path.extname)(name2);
80
90
  const { originalFilePath, query } = (0, import_utils2.resolvePathAndQuery)(name2);
81
91
  if (query.css_virtual) {
82
92
  const replacedName = (0, import_path.basename)(originalFilePath, (0, import_path.extname)(originalFilePath)).replace(".", "_");
@@ -107,12 +117,12 @@ async function redirectImport(compiler, code, modules, aliasRecord, filePath, ou
107
117
  }
108
118
  }
109
119
  if (redirect2.asset) {
110
- if (import_file.assetExt.filter((ext) => name2.endsWith(ext)).length) {
120
+ if (import_file.assetExt.filter((ext2) => name2.endsWith(ext2)).length) {
111
121
  const absPath = (0, import_path.resolve)((0, import_path.dirname)(filePath), name2);
112
122
  const svgrResult = await (0, import_asset.loadSvgr)(absPath, asset.svgr);
113
123
  if (svgrResult) {
114
- const ext = (0, import_path.extname)(name2);
115
- const outputName = `${name2.slice(0, -ext.length)}.js`;
124
+ const ext2 = (0, import_path.extname)(name2);
125
+ const outputName = `${name2.slice(0, -ext2.length)}.js`;
116
126
  str.overwrite(start, end, outputName);
117
127
  } else {
118
128
  const { contents: relativeImportPath } = await import_asset.getAssetContents.apply(compiler, [
@@ -145,7 +155,8 @@ const redirect = {
145
155
  return args;
146
156
  }
147
157
  const { code, path: id } = args;
148
- const { format, alias, sourceDir, outDir } = compiler.config;
158
+ const { format, alias, sourceDir, outDir, autoExtension } = compiler.config;
159
+ const { root } = compiler.context;
149
160
  if (!code || format === "iife" || format === "umd") {
150
161
  return args;
151
162
  }
@@ -204,8 +215,13 @@ const redirect = {
204
215
  if (!matchModule.length) {
205
216
  return args;
206
217
  }
218
+ const { jsExtension } = (0, import_utils2.getDefaultOutExtension)({
219
+ format,
220
+ root,
221
+ autoExtension
222
+ });
207
223
  const outputPath = (0, import_path.resolve)(outDir, (0, import_path.relative)(sourceDir, id));
208
- const str = await redirectImport(compiler, code, matchModule, absoluteAlias, id, (0, import_path.dirname)(outputPath), matchPath);
224
+ const str = await redirectImport(compiler, code, matchModule, absoluteAlias, id, (0, import_path.dirname)(outputPath), jsExtension, matchPath);
209
225
  return {
210
226
  ...args,
211
227
  code: str.toString(),
@@ -120,8 +120,10 @@ const mergeDefaultBaseConfig = async (pConfig, options) => {
120
120
  };
121
121
  var _pConfig_esbuildOptions;
122
122
  const esbuildOptions = (_pConfig_esbuildOptions = pConfig.esbuildOptions) !== null && _pConfig_esbuildOptions !== void 0 ? _pConfig_esbuildOptions : defaultConfig.esbuildOptions;
123
- var _pConfig_footer, _pConfig_banner, _pConfig_hooks, _pConfig_format, _pConfig_target, _pConfig_sourceMap, _pConfig_copy, _pConfig_outDir, _pConfig_jsx, _pConfig_splitting, _pConfig_minify, _pConfig_umdModuleName, _pConfig_sideEffects, _pConfig_style_inject, _pConfig_style_modules, _pConfig_style_autoModules, _pConfig_style_tailwindcss, _pConfig_externalHelpers, _pConfig_transformCache, _pConfig_transformImport, _pConfig_transformLodash, _pConfig_sourceType, _pConfig_disableSwcTransform;
123
+ var _pConfig_shims, _pConfig_autoExtension, _pConfig_footer, _pConfig_banner, _pConfig_hooks, _pConfig_format, _pConfig_target, _pConfig_sourceMap, _pConfig_copy, _pConfig_outDir, _pConfig_jsx, _pConfig_splitting, _pConfig_minify, _pConfig_umdModuleName, _pConfig_sideEffects, _pConfig_style_inject, _pConfig_style_modules, _pConfig_style_autoModules, _pConfig_style_tailwindcss, _pConfig_externalHelpers, _pConfig_transformCache, _pConfig_transformImport, _pConfig_transformLodash, _pConfig_sourceType, _pConfig_disableSwcTransform;
124
124
  return {
125
+ shims: (_pConfig_shims = pConfig.shims) !== null && _pConfig_shims !== void 0 ? _pConfig_shims : defaultConfig.shims,
126
+ autoExtension: (_pConfig_autoExtension = pConfig.autoExtension) !== null && _pConfig_autoExtension !== void 0 ? _pConfig_autoExtension : defaultConfig.autoExtension,
125
127
  footer: (_pConfig_footer = pConfig.footer) !== null && _pConfig_footer !== void 0 ? _pConfig_footer : defaultConfig.footer,
126
128
  banner: (_pConfig_banner = pConfig.banner) !== null && _pConfig_banner !== void 0 ? _pConfig_banner : defaultConfig.banner,
127
129
  resolve,
@@ -106,6 +106,9 @@ export declare const buildConfig: {
106
106
  type: string;
107
107
  };
108
108
  };
109
+ autoExtension: {
110
+ type: string;
111
+ };
109
112
  externals: {
110
113
  type: string;
111
114
  items: {
@@ -174,6 +177,9 @@ export declare const buildConfig: {
174
177
  instanceof?: undefined;
175
178
  })[];
176
179
  };
180
+ shims: {
181
+ type: string;
182
+ };
177
183
  sideEffects: {
178
184
  anyOf: ({
179
185
  type: string;
@@ -308,6 +314,9 @@ export declare const buildConfig: {
308
314
  type: string;
309
315
  };
310
316
  };
317
+ autoExtension: {
318
+ type: string;
319
+ };
311
320
  externals: {
312
321
  type: string;
313
322
  items: {
@@ -376,6 +385,9 @@ export declare const buildConfig: {
376
385
  instanceof?: undefined;
377
386
  })[];
378
387
  };
388
+ shims: {
389
+ type: string;
390
+ };
379
391
  sideEffects: {
380
392
  anyOf: ({
381
393
  type: string;
@@ -538,6 +550,9 @@ export declare const schema: ({
538
550
  type: string;
539
551
  };
540
552
  };
553
+ autoExtension: {
554
+ type: string;
555
+ };
541
556
  externals: {
542
557
  type: string;
543
558
  items: {
@@ -606,6 +621,9 @@ export declare const schema: ({
606
621
  instanceof?: undefined;
607
622
  })[];
608
623
  };
624
+ shims: {
625
+ type: string;
626
+ };
609
627
  sideEffects: {
610
628
  anyOf: ({
611
629
  type: string;
@@ -740,6 +758,9 @@ export declare const schema: ({
740
758
  type: string;
741
759
  };
742
760
  };
761
+ autoExtension: {
762
+ type: string;
763
+ };
743
764
  externals: {
744
765
  type: string;
745
766
  items: {
@@ -808,6 +829,9 @@ export declare const schema: ({
808
829
  instanceof?: undefined;
809
830
  })[];
810
831
  };
832
+ shims: {
833
+ type: string;
834
+ };
811
835
  sideEffects: {
812
836
  anyOf: ({
813
837
  type: string;
@@ -167,6 +167,9 @@ const buildConfigProperties = {
167
167
  type: "boolean"
168
168
  }
169
169
  },
170
+ autoExtension: {
171
+ type: "boolean"
172
+ },
170
173
  externals: {
171
174
  type: "array",
172
175
  items: {
@@ -262,6 +265,9 @@ const buildConfigProperties = {
262
265
  }
263
266
  ]
264
267
  },
268
+ shims: {
269
+ type: "boolean"
270
+ },
265
271
  sideEffects: {
266
272
  anyOf: [
267
273
  {
@@ -44,6 +44,7 @@ const getDefaultBuildConfig = () => {
44
44
  abortOnError: true,
45
45
  respectExternal: true
46
46
  }),
47
+ autoExtension: false,
47
48
  esbuildOptions: (c) => c,
48
49
  externalHelpers: false,
49
50
  externals: [],
@@ -61,7 +62,8 @@ const getDefaultBuildConfig = () => {
61
62
  redirect: {
62
63
  alias: true,
63
64
  asset: true,
64
- style: true
65
+ style: true,
66
+ autoExtension: true
65
67
  },
66
68
  resolve: {
67
69
  mainFields: [
@@ -76,6 +78,7 @@ const getDefaultBuildConfig = () => {
76
78
  ".json"
77
79
  ]
78
80
  },
81
+ shims: false,
79
82
  sideEffects: void 0,
80
83
  sourceDir: "./src",
81
84
  sourceMap: false,
@@ -36,6 +36,7 @@ export type Redirect = {
36
36
  alias?: boolean;
37
37
  style?: boolean;
38
38
  asset?: boolean;
39
+ autoExtension?: boolean;
39
40
  };
40
41
  export type DTSOptions = {
41
42
  abortOnError: boolean;
@@ -92,6 +93,8 @@ export type BaseBuildConfig = Omit<Required<PartialBaseBuildConfig>, 'dts' | 'st
92
93
  resolve: Required<Resolve>;
93
94
  };
94
95
  export type PartialBaseBuildConfig = {
96
+ shims?: boolean;
97
+ autoExtension?: boolean;
95
98
  resolve?: Resolve;
96
99
  footer?: BannerAndFooter;
97
100
  banner?: BannerAndFooter;
@@ -12,6 +12,7 @@ export interface GeneratorDtsConfig {
12
12
  externals: BaseBuildConfig['externals'];
13
13
  input: Input;
14
14
  respectExternal: boolean;
15
+ dtsExtension: string;
15
16
  }
16
17
  export interface GeneratedDtsInfo {
17
18
  userTsconfig: ITsconfig;
package/dist/utils/dts.js CHANGED
@@ -125,13 +125,18 @@ const resolveAlias = async (config, options, watchFilenames = []) => {
125
125
  return result;
126
126
  };
127
127
  const writeDtsFiles = async (config, options, result) => {
128
- const { distPath } = config;
128
+ const { distPath, dtsExtension } = config;
129
129
  const { tempDistAbsSrcPath } = options;
130
- for (const r of result) {
131
- import_utils.fs.writeFileSync(r.path, r.content);
132
- }
133
- await import_utils.fs.ensureDir(distPath);
134
- await import_utils.fs.copy(tempDistAbsSrcPath, distPath);
130
+ await Promise.all(result.map(({ path, content }) => {
131
+ const relativePath = (0, import_path.relative)(tempDistAbsSrcPath, path);
132
+ const filepath = (0, import_path.join)(distPath, relativePath.replace(/\.d\.ts/, dtsExtension));
133
+ import_utils.fs.ensureFileSync(filepath);
134
+ return import_utils.fs.writeFile(
135
+ // only replace .d.ts, if tsc generate .d.m(c)ts, keep.
136
+ filepath,
137
+ content
138
+ );
139
+ }));
135
140
  };
136
141
  const addBannerAndFooter = (result, banner, footer) => {
137
142
  return result.map(({ path, content }) => {
@@ -8,4 +8,5 @@ export * from './log';
8
8
  export * from './map';
9
9
  export * from './print';
10
10
  export * from './style';
11
- export * from './tspath';
11
+ export * from './tspath';
12
+ export * from './outExtension';
@@ -26,6 +26,7 @@ __reExport(utils_exports, require("./map"), module.exports);
26
26
  __reExport(utils_exports, require("./print"), module.exports);
27
27
  __reExport(utils_exports, require("./style"), module.exports);
28
28
  __reExport(utils_exports, require("./tspath"), module.exports);
29
+ __reExport(utils_exports, require("./outExtension"), module.exports);
29
30
  // Annotate the CommonJS export names for ESM import in node:
30
31
  0 && (module.exports = {
31
32
  ...require("./assert"),
@@ -38,5 +39,6 @@ __reExport(utils_exports, require("./tspath"), module.exports);
38
39
  ...require("./map"),
39
40
  ...require("./print"),
40
41
  ...require("./style"),
41
- ...require("./tspath")
42
+ ...require("./tspath"),
43
+ ...require("./outExtension")
42
44
  });
@@ -0,0 +1,9 @@
1
+ import type { Format } from '../types';
2
+ export declare const getDefaultOutExtension: (options: {
3
+ format: Format;
4
+ root: string;
5
+ autoExtension: boolean;
6
+ }) => {
7
+ jsExtension: string;
8
+ dtsExtension: string;
9
+ };
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var outExtension_exports = {};
30
+ __export(outExtension_exports, {
31
+ getDefaultOutExtension: () => getDefaultOutExtension
32
+ });
33
+ module.exports = __toCommonJS(outExtension_exports);
34
+ var import_path = __toESM(require("path"));
35
+ var import_utils = require("@modern-js/utils");
36
+ const getDefaultOutExtension = (options) => {
37
+ const { format, root, autoExtension } = options;
38
+ let jsExtension = ".js";
39
+ let dtsExtension = ".d.ts";
40
+ if (!autoExtension) {
41
+ return {
42
+ jsExtension,
43
+ dtsExtension
44
+ };
45
+ }
46
+ let isModule = false;
47
+ try {
48
+ const json = JSON.parse(import_utils.fs.readFileSync(import_path.default.resolve(root, "./package.json"), "utf8"));
49
+ isModule = json.type === "module";
50
+ } catch (e) {
51
+ import_utils.logger.warn("package.json is broken");
52
+ return {
53
+ jsExtension,
54
+ dtsExtension
55
+ };
56
+ }
57
+ if (isModule && format === "cjs") {
58
+ jsExtension = ".cjs";
59
+ dtsExtension = ".d.cts";
60
+ }
61
+ if (!isModule && format === "esm") {
62
+ jsExtension = ".mjs";
63
+ dtsExtension = ".d.mts";
64
+ }
65
+ return {
66
+ jsExtension,
67
+ dtsExtension
68
+ };
69
+ };
70
+ // Annotate the CommonJS export names for ESM import in node:
71
+ 0 && (module.exports = {
72
+ getDefaultOutExtension
73
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@modern-js/module-tools",
3
- "version": "2.37.1",
3
+ "version": "2.38.0-beta.0",
4
4
  "description": "Simple, powerful, high-performance modern npm package development solution.",
5
5
  "keywords": [
6
6
  "modern",
@@ -71,14 +71,14 @@
71
71
  "tapable": "2.2.1",
72
72
  "terser": "5.19.2",
73
73
  "tsconfig-paths-webpack-plugin": "4.1.0",
74
+ "@modern-js/plugin-changeset": "2.37.1",
74
75
  "@modern-js/core": "2.37.1",
75
76
  "@modern-js/new-action": "2.37.1",
76
77
  "@modern-js/plugin": "2.37.1",
77
- "@modern-js/plugin-changeset": "2.37.1",
78
78
  "@modern-js/plugin-i18n": "2.37.1",
79
79
  "@modern-js/plugin-lint": "2.37.1",
80
- "@modern-js/types": "2.37.1",
81
80
  "@modern-js/upgrade": "2.37.1",
81
+ "@modern-js/types": "2.37.1",
82
82
  "@modern-js/utils": "2.37.1"
83
83
  },
84
84
  "devDependencies": {
@@ -88,8 +88,8 @@
88
88
  "@types/node": "^14",
89
89
  "typescript": "^5",
90
90
  "@modern-js/builder-webpack-provider": "2.37.1",
91
- "@modern-js/self": "npm:@modern-js/module-tools@2.37.1",
92
91
  "@scripts/build": "2.37.1",
92
+ "@modern-js/self": "npm:@modern-js/module-tools@2.38.0-beta.0",
93
93
  "@scripts/vitest-config": "2.37.1"
94
94
  },
95
95
  "peerDependencies": {
package/shims/cjs.js ADDED
@@ -0,0 +1,17 @@
1
+ /* eslint-disable node/prefer-global/url */
2
+ /* eslint-disable no-undef */
3
+ // taking from https://github.com/egoist/tsup/blob/dev/assets/cjs_shims.js
4
+
5
+ // Shim globals in cjs bundle
6
+ // There's a weird bug that esbuild will always inject importMetaUrl
7
+ // if we export it as `const importMetaUrl = ... __filename ...`
8
+ // But using a function will not cause this issue
9
+
10
+ const getImportMetaUrl = () =>
11
+ typeof document === 'undefined'
12
+ ? new URL(`file:${__filename}`).href
13
+ : (document.currentScript && document.currentScript.src) ||
14
+ new URL('main.js', document.baseURI).href;
15
+
16
+ // define importMetaUrl
17
+ export const importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
package/shims/esm.js ADDED
@@ -0,0 +1,9 @@
1
+ // Shim globals in esm bundle
2
+ import { fileURLToPath } from 'url';
3
+ import path from 'path';
4
+
5
+ const getFilename = () => fileURLToPath(import.meta.url);
6
+ const getDirname = () => path.dirname(getFilename());
7
+
8
+ export const __dirname = /* @__PURE__ */ getDirname();
9
+ export const __filename = /* @__PURE__ */ getFilename();