@es-pkg/compile 1.0.7 → 1.0.8

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.
Files changed (3) hide show
  1. package/cjs/index.js +150 -177
  2. package/esm/index.js +161 -175
  3. package/package.json +1 -1
package/cjs/index.js CHANGED
@@ -1,230 +1,203 @@
1
1
  'use strict';
2
2
 
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __export = (target, all) => {
10
- for (var name2 in all)
11
- __defProp(target, name2, { get: all[name2], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
- var src_exports = {};
31
- __export(src_exports, {
32
- default: () => src_default
33
- });
34
- module.exports = __toCommonJS(src_exports);
35
- var import_gulp = __toESM(require("@es-pkg/gulp"));
36
- var import_utils = require("@es-pkg/utils");
37
- var import_config = require("@es-pkg/config");
38
- var import_rollup = require("rollup");
39
- var import_plugin_node_resolve = __toESM(require("@rollup/plugin-node-resolve"));
40
- var import_plugin_commonjs = __toESM(require("@rollup/plugin-commonjs"));
41
- var import_plugin_typescript = __toESM(require("@rollup/plugin-typescript"));
42
- var import_plugin_json = __toESM(require("@rollup/plugin-json"));
43
- var import_rollup_plugin_postcss = __toESM(require("rollup-plugin-postcss"));
44
- var import_autoprefixer = __toESM(require("autoprefixer"));
45
- var import_cssnano = __toESM(require("cssnano"));
46
- var import_node_path = __toESM(require("node:path"));
47
- var import_node_fs = __toESM(require("node:fs"));
48
- var import_rollup_plugin_esbuild = __toESM(require("rollup-plugin-esbuild"));
49
- var import_node_module = require("node:module");
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var gulp = require('@es-pkg/gulp');
6
+ var utils = require('@es-pkg/utils');
7
+ var config = require('@es-pkg/config');
8
+ var rollup = require('rollup');
9
+ var resolve = require('@rollup/plugin-node-resolve');
10
+ var commonjs = require('@rollup/plugin-commonjs');
11
+ var json = require('@rollup/plugin-json');
12
+ var postcss = require('rollup-plugin-postcss');
13
+ var autoprefixer = require('autoprefixer');
14
+ var cssnano = require('cssnano');
15
+ var path = require('node:path');
16
+ var fs = require('node:fs');
17
+ var esbuild = require('rollup-plugin-esbuild');
18
+ var node_module = require('node:module');
19
+ var ts = require('typescript');
20
+
21
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
22
+
23
+ var gulp__default = /*#__PURE__*/_interopDefault(gulp);
24
+ var resolve__default = /*#__PURE__*/_interopDefault(resolve);
25
+ var commonjs__default = /*#__PURE__*/_interopDefault(commonjs);
26
+ var json__default = /*#__PURE__*/_interopDefault(json);
27
+ var postcss__default = /*#__PURE__*/_interopDefault(postcss);
28
+ var autoprefixer__default = /*#__PURE__*/_interopDefault(autoprefixer);
29
+ var cssnano__default = /*#__PURE__*/_interopDefault(cssnano);
30
+ var path__default = /*#__PURE__*/_interopDefault(path);
31
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
32
+ var esbuild__default = /*#__PURE__*/_interopDefault(esbuild);
33
+ var ts__default = /*#__PURE__*/_interopDefault(ts);
34
+
35
+ const name = utils.getValidPkgName(config.pkg.name);
50
36
  const clean = () => {
51
- (0, import_utils.log)(`\u6E05\u9664 ${(0, import_config.relativeToApp)(import_config.config.es)} & ${(0, import_config.relativeToApp)(import_config.config.cjs)} \u76EE\u5F55---\u5F00\u59CB`);
37
+ utils.log(`\u6E05\u9664 ${config.relativeToApp(config.config.es)} & ${config.relativeToApp(config.config.cjs)} \u76EE\u5F55---\u5F00\u59CB`);
52
38
  const promises = [
53
- (0, import_utils.remove)(import_config.config.publishDir, true),
54
- (0, import_utils.remove)(import_config.config.es, true),
55
- (0, import_utils.remove)(import_config.config.cjs, true),
56
- (0, import_utils.remove)(import_config.config.iife, true)
39
+ utils.remove(config.config.publishDir, true),
40
+ utils.remove(config.config.es, true),
41
+ utils.remove(config.config.cjs, true),
42
+ utils.remove(config.config.iife, true)
57
43
  ];
58
- return Promise.all(promises).then((res) => {
59
- (0, import_utils.log)(`\u6E05\u9664 ${(0, import_config.relativeToApp)(import_config.config.es)} & ${(0, import_config.relativeToApp)(import_config.config.cjs)} \u76EE\u5F55---\u7ED3\u675F`);
44
+ return Promise.all(promises).then(() => {
45
+ utils.log(`\u6E05\u9664 ${config.relativeToApp(config.config.es)} & ${config.relativeToApp(config.config.cjs)} \u76EE\u5F55---\u7ED3\u675F`);
60
46
  });
61
47
  };
62
48
  function getPostcss(extract) {
63
- return (0, import_rollup_plugin_postcss.default)({
64
- // 处理 Less(需安装 less)
49
+ return postcss__default.default({
65
50
  extensions: [".less", ".scss", ".sass"],
66
- // 识别 less 扩展名
67
- // 为不同类型的文件指定对应的编译器(关键修改)
68
51
  use: {
69
- "stylus": ["sass"],
70
- "less": ["less"],
71
- //.less 文件用 less 编译
72
- "sass": ["sass"]
73
- //.sass 文件用 sass 编译(缩进语法)
52
+ stylus: ["sass"],
53
+ less: ["less"],
54
+ sass: ["sass"]
74
55
  },
75
- // 配置 PostCSS 插件(自动前缀、压缩)
76
- plugins: [
77
- (0, import_autoprefixer.default)({ overrideBrowserslist: import_config.config.css.browserslist }),
78
- (0, import_cssnano.default)()
79
- // 生产环境压缩 CSS
80
- ],
81
- // 输出配置:提取为单独的 CSS 文件(推荐)
56
+ plugins: [autoprefixer__default.default({ overrideBrowserslist: config.config.css.browserslist }), cssnano__default.default()],
82
57
  extract
83
- // 提取到 ${name}.min.css
84
- // 可选:不提取,嵌入到 JS 中(通过 import 会生成 style 标签)
85
- // extract: false
86
58
  });
87
59
  }
88
- const name = (0, import_utils.getValidPkgName)(import_config.pkg.name);
89
- function getInputOptions(format, declarationDir) {
90
- function isNodeModule(id) {
91
- try {
92
- const resolved = require.resolve(id, { paths: [process.cwd()] });
93
- return resolved.includes("node_modules");
94
- } catch {
95
- return false;
96
- }
60
+ function isNodeModule(id) {
61
+ try {
62
+ const resolved = require.resolve(id, { paths: [process.cwd()] });
63
+ return resolved.includes("node_modules");
64
+ } catch (e) {
65
+ return false;
97
66
  }
67
+ }
68
+ function getInputOptions(format) {
98
69
  return {
99
- input: import_config.shallowInputs.filter((item) => !item.endsWith(".d.ts")),
70
+ input: config.shallowInputs.filter((item) => !item.endsWith(".d.ts")),
100
71
  external: (id) => {
101
- if (import_node_module.builtinModules.includes(id))
102
- return true;
103
- if (id.startsWith(".") || import_node_path.default.isAbsolute(id))
104
- return false;
105
- return isNodeModule(id);
72
+ if (node_module.builtinModules.includes(id)) return true;
73
+ if (!id.startsWith(".") && !path__default.default.isAbsolute(id) && isNodeModule(id)) return true;
74
+ return false;
106
75
  },
107
76
  plugins: [
108
- (0, import_plugin_json.default)(),
109
- format === "iife" && (0, import_plugin_node_resolve.default)(),
110
- // 解析 node_modules
111
- format === "iife" && (0, import_plugin_commonjs.default)({ defaultIsModuleExports: true }),
112
- // 转换 CommonJS 模块
113
- (0, import_plugin_typescript.default)({
114
- tsconfig: (0, import_config.resolveApp)("tsconfig.json"),
115
- // 可选,指定 tsconfig
116
- compilerOptions: {
117
- module: "esnext",
118
- esModuleInterop: true,
119
- allowSyntheticDefaultImports: true,
120
- noImplicitAny: true,
121
- isolatedModules: false,
122
- declaration: !!declarationDir,
123
- declarationDir,
124
- noEmit: false,
125
- emitDeclarationOnly: !!declarationDir,
126
- resolveJsonModule: true,
127
- skipLibCheck: true,
128
- removeComments: false,
129
- rootDir: (0, import_config.resolveApp)("src")
130
- // ✅ 指定源代码根目录
131
- }
132
- }),
133
- ["cjs", "commonjs"].includes(format) && (0, import_rollup_plugin_esbuild.default)({
134
- target: "esnext",
135
- format: "cjs"
77
+ json__default.default(),
78
+ resolve__default.default(),
79
+ esbuild__default.default({ target: "es2018", format: "esm" }),
80
+ commonjs__default.default({
81
+ defaultIsModuleExports: true,
82
+ esmExternals: true,
83
+ transformMixedEsModules: true
84
+ // 混合模块也转换
136
85
  }),
137
- getPostcss(import_config.config.css.extract)
138
- ].filter(Boolean)
86
+ getPostcss(config.config.css.extract)
87
+ ]
139
88
  };
140
89
  }
90
+ async function buildDeclarations() {
91
+ const tsConfig = ts__default.default.readConfigFile(config.resolveApp("tsconfig.json"), ts__default.default.sys.readFile);
92
+ if (tsConfig.error) {
93
+ console.log(tsConfig.error.messageText);
94
+ }
95
+ const entryFiles = config.collectInputs.filter((item) => [".ts", ".tsx"].some((suf) => item.endsWith(suf)));
96
+ const compilerOptions = {
97
+ ...tsConfig.config,
98
+ declaration: true,
99
+ emitDeclarationOnly: true,
100
+ outDir: config.config.es,
101
+ rootDir: config.resolveApp("src"),
102
+ skipLibCheck: true,
103
+ esModuleInterop: true,
104
+ moduleResolution: ts__default.default.ModuleResolutionKind.NodeJs,
105
+ target: ts__default.default.ScriptTarget.ESNext,
106
+ module: ts__default.default.ModuleKind.ESNext
107
+ };
108
+ const host = ts__default.default.createCompilerHost(compilerOptions);
109
+ host.writeFile = (fileName, contents) => {
110
+ const dir = path__default.default.dirname(fileName);
111
+ fs__default.default.mkdirSync(dir, { recursive: true });
112
+ fs__default.default.writeFileSync(fileName, contents, "utf8");
113
+ };
114
+ const program = ts__default.default.createProgram(entryFiles, compilerOptions, host);
115
+ const emitResult = program.emit();
116
+ const diagnostics = ts__default.default.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
117
+ if (diagnostics.length > 0) {
118
+ console.error(
119
+ ts__default.default.formatDiagnosticsWithColorAndContext(diagnostics, {
120
+ getCanonicalFileName: (f) => f,
121
+ getCurrentDirectory: ts__default.default.sys.getCurrentDirectory,
122
+ getNewLine: () => ts__default.default.sys.newLine
123
+ })
124
+ );
125
+ } else {
126
+ console.log(`\u2705 Declarations generated in: ${path__default.default.resolve(config.config.es)}`);
127
+ }
128
+ utils.log.success("\u2705 Declarations build complete!");
129
+ }
141
130
  async function buildExtraCss() {
142
- const extras = import_config.config.css.extra;
143
- if (!extras?.length)
144
- return;
145
- const srcRoot = (0, import_config.resolveApp)("src");
146
- const esRoot = (0, import_config.resolveApp)(import_config.config.es);
131
+ const extras = config.config.css.extra;
132
+ if (!(extras == null ? void 0 : extras.length)) return;
133
+ const srcRoot = config.resolveApp("src");
134
+ const esRoot = config.resolveApp(config.config.es);
147
135
  const tasks = extras.map(async (v) => {
148
136
  try {
149
- const absPath = (0, import_config.resolveApp)(v);
150
- const relativePath = import_node_path.default.relative(srcRoot, absPath);
151
- const dirname = import_node_path.default.dirname(relativePath);
152
- const filename = import_node_path.default.basename(v, import_node_path.default.extname(v));
153
- const bundle = await (0, import_rollup.rollup)({
137
+ const absPath = config.resolveApp(v);
138
+ const relativePath = path__default.default.relative(srcRoot, absPath);
139
+ const dirname = path__default.default.dirname(relativePath);
140
+ const filename = path__default.default.basename(v, path__default.default.extname(v));
141
+ const bundle = await rollup.rollup({
154
142
  input: [v],
155
- plugins: getPostcss(import_node_path.default.join(dirname, `${filename}.min.css`))
143
+ plugins: getPostcss(path__default.default.join(dirname, `${filename}.min.css`))
156
144
  });
157
145
  await bundle.write({
158
- dir: import_config.config.es,
146
+ dir: config.config.es,
159
147
  format: "es",
160
148
  sourcemap: false,
161
149
  preserveModules: true,
162
150
  preserveModulesRoot: srcRoot
163
151
  });
164
- const jsFile = import_node_path.default.join(esRoot, dirname, `${filename}${import_node_path.default.extname(v)}.js`);
165
- if (import_node_fs.default.existsSync(jsFile))
166
- import_node_fs.default.unlinkSync(jsFile);
167
- [import_config.config.cjs, import_config.config.iife].forEach((targetRoot) => {
168
- const dest = import_node_path.default.join((0, import_config.resolveApp)(targetRoot), dirname, `${filename}.min.css`);
169
- import_node_fs.default.mkdirSync(import_node_path.default.dirname(dest), { recursive: true });
170
- import_node_fs.default.copyFileSync(import_node_path.default.join(esRoot, dirname, `${filename}.min.css`), dest);
152
+ const jsFile = path__default.default.join(esRoot, dirname, `${filename}${path__default.default.extname(v)}.js`);
153
+ if (fs__default.default.existsSync(jsFile)) fs__default.default.unlinkSync(jsFile);
154
+ [config.config.cjs, config.config.iife].forEach((targetRoot) => {
155
+ const dest = path__default.default.join(config.resolveApp(targetRoot), dirname, `${filename}.min.css`);
156
+ fs__default.default.mkdirSync(path__default.default.dirname(dest), { recursive: true });
157
+ fs__default.default.copyFileSync(path__default.default.join(esRoot, dirname, `${filename}.min.css`), dest);
171
158
  });
172
- import_utils.log.success(`\u2705 \u7F16\u8BD1\u5B8C\u6210: ${v}`);
159
+ utils.log.success(`\u2705 \u7F16\u8BD1\u5B8C\u6210: ${v}`);
173
160
  } catch (err) {
174
- import_utils.log.error(`\u274C \u7F16\u8BD1\u5931\u8D25: ${v}`, err);
161
+ utils.log.error(`\u274C \u7F16\u8BD1\u5931\u8D25: ${v}`, err);
175
162
  }
176
163
  });
177
164
  await Promise.all(tasks);
178
- import_utils.log.success("\u2705 \u6240\u6709\u989D\u5916 CSS \u7F16\u8BD1\u5B8C\u6210");
165
+ utils.log.success("\u2705 \u6240\u6709\u989D\u5916 CSS \u7F16\u8BD1\u5B8C\u6210");
179
166
  }
180
- async function build() {
181
- let outputOptions = [
167
+ async function buildJS() {
168
+ const outputOptions = [
182
169
  {
183
- dir: import_config.config.es,
170
+ dir: config.config.es,
184
171
  format: "es",
185
- // 输出 ES Module
186
- sourcemap: false,
187
172
  preserveModules: true,
188
- preserveModulesRoot: (0, import_config.resolveApp)("src")
189
- // ✅ 指定源代码根目录
173
+ preserveModulesRoot: config.resolveApp("src")
190
174
  },
191
175
  {
192
- dir: import_config.config.cjs,
176
+ dir: config.config.cjs,
193
177
  format: "cjs",
194
- // 输出 COMMONJS
195
- sourcemap: false,
196
178
  preserveModules: true,
197
- preserveModulesRoot: (0, import_config.resolveApp)("src"),
198
- // ✅ 指定源代码根目录
199
- exports: "named"
200
- },
201
- {
202
- dir: import_config.config.iife,
203
- format: "iife",
204
- // 输出 iife
205
- sourcemap: false,
179
+ preserveModulesRoot: config.resolveApp("src"),
206
180
  exports: "named",
207
- name: (0, import_utils.toPascalCase)(name)
208
- }
181
+ interop: "auto"
182
+ },
183
+ ...config.config.iife ? [
184
+ {
185
+ dir: config.config.iife,
186
+ format: "iife",
187
+ exports: "named",
188
+ name: utils.toPascalCase(name)
189
+ }
190
+ ] : []
209
191
  ];
210
- if (!import_config.config.iife) {
211
- outputOptions = outputOptions.filter((op) => op.format !== "iife");
212
- }
213
192
  for (const output of outputOptions) {
214
- const bundle = await (0, import_rollup.rollup)(getInputOptions(output.format));
193
+ const bundle = await rollup.rollup(getInputOptions(output.format));
215
194
  await bundle.write(output);
216
195
  }
217
- {
218
- const bundle = await (0, import_rollup.rollup)(getInputOptions("es", import_config.config.es));
219
- await bundle.write(outputOptions[0]);
220
- }
221
196
  await buildExtraCss();
222
- import_utils.log.success("\u2705 Build complete!");
197
+ utils.log.success("\u2705 JS Build complete!");
223
198
  }
224
- const copySrcTds = () => {
225
- return import_gulp.default.src(import_config.config.include.map((t) => `${t}/**/*.d.ts`)).pipe(import_gulp.default.dest(import_config.config.es));
226
- };
227
- const copyTds = () => {
228
- return import_gulp.default.src([`${import_config.config.es}/**/*.d.ts`]).pipe(import_gulp.default.dest(import_config.config.cjs));
229
- };
230
- var src_default = (0, import_gulp.series)(clean, build, copySrcTds, copyTds);
199
+ const copySrcTds = () => gulp__default.default.src(config.config.include.map((t) => `${t}/**/*.d.ts`)).pipe(gulp__default.default.dest(config.config.es));
200
+ const copyTds = () => gulp__default.default.src([`${config.config.es}/**/*.d.ts`]).pipe(gulp__default.default.dest(config.config.cjs));
201
+ var src_default = gulp.series(clean, buildJS, buildDeclarations, copySrcTds, copyTds);
202
+
203
+ exports.default = src_default;
package/esm/index.js CHANGED
@@ -1,10 +1,9 @@
1
1
  import gulp, { series } from '@es-pkg/gulp';
2
2
  import { getValidPkgName, log, remove, toPascalCase } from '@es-pkg/utils';
3
- import { pkg, relativeToApp, config, resolveApp, shallowInputs } from '@es-pkg/config';
3
+ import { pkg, relativeToApp, config, resolveApp, collectInputs, shallowInputs } from '@es-pkg/config';
4
4
  import { rollup } from 'rollup';
5
5
  import resolve from '@rollup/plugin-node-resolve';
6
6
  import commonjs from '@rollup/plugin-commonjs';
7
- import typescript from '@rollup/plugin-typescript';
8
7
  import json from '@rollup/plugin-json';
9
8
  import postcss from 'rollup-plugin-postcss';
10
9
  import autoprefixer from 'autoprefixer';
@@ -13,187 +12,174 @@ import path from 'node:path';
13
12
  import fs from 'node:fs';
14
13
  import esbuild from 'rollup-plugin-esbuild';
15
14
  import { builtinModules } from 'node:module';
15
+ import ts from 'typescript';
16
16
 
17
+ const name = getValidPkgName(pkg.name);
17
18
  const clean = () => {
18
- log(`清除 ${relativeToApp(config.es)} & ${relativeToApp(config.cjs)} 目录---开始`);
19
- const promises = [
20
- remove(config.publishDir, true),
21
- remove(config.es, true),
22
- remove(config.cjs, true),
23
- remove(config.iife, true),
24
- ];
25
- return Promise.all(promises).then(res => {
26
- log(`清除 ${relativeToApp(config.es)} & ${relativeToApp(config.cjs)} 目录---结束`);
27
- });
19
+ log(`\u6E05\u9664 ${relativeToApp(config.es)} & ${relativeToApp(config.cjs)} \u76EE\u5F55---\u5F00\u59CB`);
20
+ const promises = [
21
+ remove(config.publishDir, true),
22
+ remove(config.es, true),
23
+ remove(config.cjs, true),
24
+ remove(config.iife, true)
25
+ ];
26
+ return Promise.all(promises).then(() => {
27
+ log(`\u6E05\u9664 ${relativeToApp(config.es)} & ${relativeToApp(config.cjs)} \u76EE\u5F55---\u7ED3\u675F`);
28
+ });
28
29
  };
29
30
  function getPostcss(extract) {
30
- return postcss({
31
- // 处理 Less(需安装 less)
32
- extensions: ['.less', '.scss', '.sass'], // 识别 less 扩展名
33
- // 为不同类型的文件指定对应的编译器(关键修改)
34
- use: {
35
- "stylus": ['sass'],
36
- 'less': ['less'], //.less 文件用 less 编译
37
- 'sass': ['sass'] //.sass 文件用 sass 编译(缩进语法)
38
- },
39
- // 配置 PostCSS 插件(自动前缀、压缩)
40
- plugins: [
41
- autoprefixer({ overrideBrowserslist: config.css.browserslist }),
42
- cssnano() // 生产环境压缩 CSS
43
- ],
44
- // 输出配置:提取为单独的 CSS 文件(推荐)
45
- extract, // 提取到 ${name}.min.css
46
- // 可选:不提取,嵌入到 JS 中(通过 import 会生成 style 标签)
47
- // extract: false
48
- });
31
+ return postcss({
32
+ extensions: [".less", ".scss", ".sass"],
33
+ use: {
34
+ stylus: ["sass"],
35
+ less: ["less"],
36
+ sass: ["sass"]
37
+ },
38
+ plugins: [autoprefixer({ overrideBrowserslist: config.css.browserslist }), cssnano()],
39
+ extract
40
+ });
49
41
  }
50
- const name = getValidPkgName(pkg.name);
51
- // 1. 配置输入选项
52
- function getInputOptions(format, declarationDir) {
53
- function isNodeModule(id) {
54
- // 获取模块绝对路径
55
- try {
56
- const resolved = require.resolve(id, { paths: [process.cwd()] });
57
- return resolved.includes('node_modules');
58
- }
59
- catch {
60
- // 无法 resolve 的,认为是本地模块
61
- return false;
62
- }
63
- }
64
- return ({
65
- input: shallowInputs.filter(item => !item.endsWith('.d.ts')),
66
- external: id => {
67
- // Node 内置模块或者 npm 包都 external
68
- if (builtinModules.includes(id))
69
- return true;
70
- // 排除本地相对路径和绝对路径,别名映射到本地也不会 external
71
- if (id.startsWith('.') || path.isAbsolute(id))
72
- return false;
73
- // node_modules 下的模块才 external
74
- return isNodeModule(id);
75
- },
76
- plugins: [
77
- json(),
78
- format === 'iife' && resolve(), // 解析 node_modules
79
- format === 'iife' && commonjs({ defaultIsModuleExports: true }), // 转换 CommonJS 模块
80
- typescript({
81
- tsconfig: resolveApp('tsconfig.json'), // 可选,指定 tsconfig
82
- compilerOptions: {
83
- module: 'esnext',
84
- esModuleInterop: true,
85
- allowSyntheticDefaultImports: true,
86
- noImplicitAny: true,
87
- isolatedModules: false,
88
- declaration: !!declarationDir,
89
- declarationDir,
90
- noEmit: false,
91
- emitDeclarationOnly: !!declarationDir,
92
- resolveJsonModule: true,
93
- skipLibCheck: true,
94
- removeComments: false,
95
- rootDir: resolveApp('src'), // ✅ 指定源代码根目录
96
- }
97
- }),
98
- ["cjs", "commonjs"].includes(format) && esbuild({
99
- target: 'esnext',
100
- format: "cjs",
101
- }),
102
- getPostcss(config.css.extract)
103
- ].filter(Boolean)
104
- });
42
+ function isNodeModule(id) {
43
+ try {
44
+ const resolved = require.resolve(id, { paths: [process.cwd()] });
45
+ return resolved.includes("node_modules");
46
+ } catch (e) {
47
+ return false;
48
+ }
105
49
  }
106
- async function buildExtraCss() {
107
- const extras = config.css.extra;
108
- if (!extras?.length)
109
- return;
110
- const srcRoot = resolveApp('src');
111
- const esRoot = resolveApp(config.es);
112
- const tasks = extras.map(async (v) => {
113
- try {
114
- const absPath = resolveApp(v); // 源文件绝对路径
115
- const relativePath = path.relative(srcRoot, absPath); // 相对于 src 的路径
116
- const dirname = path.dirname(relativePath); // 相对目录
117
- const filename = path.basename(v, path.extname(v)); // 文件名去掉扩展名
118
- // rollup 打包
119
- const bundle = await rollup({
120
- input: [v],
121
- plugins: getPostcss(path.join(dirname, `${filename}.min.css`))
122
- });
123
- await bundle.write({
124
- dir: config.es,
125
- format: 'es',
126
- sourcemap: false,
127
- preserveModules: true,
128
- preserveModulesRoot: srcRoot
129
- });
130
- // 删除生成的 JS 文件
131
- const jsFile = path.join(esRoot, dirname, `${filename}${path.extname(v)}.js`);
132
- if (fs.existsSync(jsFile))
133
- fs.unlinkSync(jsFile);
134
- // 复制到其他目标目录
135
- [config.cjs, config.iife].forEach(targetRoot => {
136
- const dest = path.join(resolveApp(targetRoot), dirname, `${filename}.min.css`);
137
- fs.mkdirSync(path.dirname(dest), { recursive: true });
138
- fs.copyFileSync(path.join(esRoot, dirname, `${filename}.min.css`), dest);
139
- });
140
- log.success(`✅ 编译完成: ${v}`);
141
- }
142
- catch (err) {
143
- log.error(`❌ 编译失败: ${v}`, err);
144
- }
145
- });
146
- await Promise.all(tasks);
147
- log.success('✅ 所有额外 CSS 编译完成');
50
+ function getInputOptions(format) {
51
+ return {
52
+ input: shallowInputs.filter((item) => !item.endsWith(".d.ts")),
53
+ external: (id) => {
54
+ if (builtinModules.includes(id)) return true;
55
+ if (!id.startsWith(".") && !path.isAbsolute(id) && isNodeModule(id)) return true;
56
+ return false;
57
+ },
58
+ plugins: [
59
+ json(),
60
+ resolve(),
61
+ esbuild({ target: "es2018", format: "esm" }),
62
+ commonjs({
63
+ defaultIsModuleExports: true,
64
+ esmExternals: true,
65
+ transformMixedEsModules: true
66
+ // 混合模块也转换
67
+ }),
68
+ getPostcss(config.css.extract)
69
+ ]
70
+ };
148
71
  }
149
- async function build() {
150
- // 2. 配置输出选项
151
- let outputOptions = [
152
- {
153
- dir: config.es,
154
- format: 'es', // 输出 ES Module
155
- sourcemap: false,
156
- preserveModules: true,
157
- preserveModulesRoot: resolveApp('src'), // ✅ 指定源代码根目录
158
- },
159
- {
160
- dir: config.cjs,
161
- format: 'cjs', // 输出 COMMONJS
162
- sourcemap: false,
163
- preserveModules: true,
164
- preserveModulesRoot: resolveApp('src'), // ✅ 指定源代码根目录
165
- exports: "named",
166
- },
167
- {
168
- dir: config.iife,
169
- format: 'iife', // 输出 iife
170
- sourcemap: false,
171
- exports: "named",
172
- name: toPascalCase(name)
173
- }
174
- ];
175
- if (!config.iife) {
176
- outputOptions = outputOptions.filter(op => op.format !== 'iife');
177
- }
178
- for (const output of outputOptions) {
179
- // 3. 调用 rollup 打包
180
- const bundle = await rollup(getInputOptions(output.format));
181
- // 4. 写入文件
182
- await bundle.write(output);
72
+ async function buildDeclarations() {
73
+ const tsConfig = ts.readConfigFile(resolveApp("tsconfig.json"), ts.sys.readFile);
74
+ if (tsConfig.error) {
75
+ console.log(tsConfig.error.messageText);
76
+ }
77
+ const entryFiles = collectInputs.filter((item) => [".ts", ".tsx"].some((suf) => item.endsWith(suf)));
78
+ const compilerOptions = {
79
+ ...tsConfig.config,
80
+ declaration: true,
81
+ emitDeclarationOnly: true,
82
+ outDir: config.es,
83
+ rootDir: resolveApp("src"),
84
+ skipLibCheck: true,
85
+ esModuleInterop: true,
86
+ moduleResolution: ts.ModuleResolutionKind.NodeJs,
87
+ target: ts.ScriptTarget.ESNext,
88
+ module: ts.ModuleKind.ESNext
89
+ };
90
+ const host = ts.createCompilerHost(compilerOptions);
91
+ host.writeFile = (fileName, contents) => {
92
+ const dir = path.dirname(fileName);
93
+ fs.mkdirSync(dir, { recursive: true });
94
+ fs.writeFileSync(fileName, contents, "utf8");
95
+ };
96
+ const program = ts.createProgram(entryFiles, compilerOptions, host);
97
+ const emitResult = program.emit();
98
+ const diagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
99
+ if (diagnostics.length > 0) {
100
+ console.error(
101
+ ts.formatDiagnosticsWithColorAndContext(diagnostics, {
102
+ getCanonicalFileName: (f) => f,
103
+ getCurrentDirectory: ts.sys.getCurrentDirectory,
104
+ getNewLine: () => ts.sys.newLine
105
+ })
106
+ );
107
+ } else {
108
+ console.log(`\u2705 Declarations generated in: ${path.resolve(config.es)}`);
109
+ }
110
+ log.success("\u2705 Declarations build complete!");
111
+ }
112
+ async function buildExtraCss() {
113
+ const extras = config.css.extra;
114
+ if (!(extras == null ? void 0 : extras.length)) return;
115
+ const srcRoot = resolveApp("src");
116
+ const esRoot = resolveApp(config.es);
117
+ const tasks = extras.map(async (v) => {
118
+ try {
119
+ const absPath = resolveApp(v);
120
+ const relativePath = path.relative(srcRoot, absPath);
121
+ const dirname = path.dirname(relativePath);
122
+ const filename = path.basename(v, path.extname(v));
123
+ const bundle = await rollup({
124
+ input: [v],
125
+ plugins: getPostcss(path.join(dirname, `${filename}.min.css`))
126
+ });
127
+ await bundle.write({
128
+ dir: config.es,
129
+ format: "es",
130
+ sourcemap: false,
131
+ preserveModules: true,
132
+ preserveModulesRoot: srcRoot
133
+ });
134
+ const jsFile = path.join(esRoot, dirname, `${filename}${path.extname(v)}.js`);
135
+ if (fs.existsSync(jsFile)) fs.unlinkSync(jsFile);
136
+ [config.cjs, config.iife].forEach((targetRoot) => {
137
+ const dest = path.join(resolveApp(targetRoot), dirname, `${filename}.min.css`);
138
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
139
+ fs.copyFileSync(path.join(esRoot, dirname, `${filename}.min.css`), dest);
140
+ });
141
+ log.success(`\u2705 \u7F16\u8BD1\u5B8C\u6210: ${v}`);
142
+ } catch (err) {
143
+ log.error(`\u274C \u7F16\u8BD1\u5931\u8D25: ${v}`, err);
183
144
  }
145
+ });
146
+ await Promise.all(tasks);
147
+ log.success("\u2705 \u6240\u6709\u989D\u5916 CSS \u7F16\u8BD1\u5B8C\u6210");
148
+ }
149
+ async function buildJS() {
150
+ const outputOptions = [
184
151
  {
185
- const bundle = await rollup(getInputOptions('es', config.es));
186
- await bundle.write(outputOptions[0]);
187
- }
188
- await buildExtraCss();
189
- log.success('✅ Build complete!');
152
+ dir: config.es,
153
+ format: "es",
154
+ preserveModules: true,
155
+ preserveModulesRoot: resolveApp("src")
156
+ },
157
+ {
158
+ dir: config.cjs,
159
+ format: "cjs",
160
+ preserveModules: true,
161
+ preserveModulesRoot: resolveApp("src"),
162
+ exports: "named",
163
+ interop: "auto"
164
+ },
165
+ ...config.iife ? [
166
+ {
167
+ dir: config.iife,
168
+ format: "iife",
169
+ exports: "named",
170
+ name: toPascalCase(name)
171
+ }
172
+ ] : []
173
+ ];
174
+ for (const output of outputOptions) {
175
+ const bundle = await rollup(getInputOptions(output.format));
176
+ await bundle.write(output);
177
+ }
178
+ await buildExtraCss();
179
+ log.success("\u2705 JS Build complete!");
190
180
  }
191
- const copySrcTds = () => {
192
- return gulp.src(config.include.map(t => `${t}/**/*.d.ts`)).pipe(gulp.dest(config.es));
193
- };
194
- const copyTds = () => {
195
- return gulp.src([`${config.es}/**/*.d.ts`]).pipe(gulp.dest(config.cjs));
196
- };
197
- var index = series(clean, build, copySrcTds, copyTds);
181
+ const copySrcTds = () => gulp.src(config.include.map((t) => `${t}/**/*.d.ts`)).pipe(gulp.dest(config.es));
182
+ const copyTds = () => gulp.src([`${config.es}/**/*.d.ts`]).pipe(gulp.dest(config.cjs));
183
+ var src_default = series(clean, buildJS, buildDeclarations, copySrcTds, copyTds);
198
184
 
199
- export { index as default };
185
+ export { src_default as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@es-pkg/compile",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "组件打包工具",
5
5
  "main": "cjs/index.js",
6
6
  "keywords": [