@ohos-ports/rollup-plugin-esbuild 0.0.0-stage → 5.0.0-beta.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 EGOIST
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ **💛 You can help the author become a full-time open-source maintainer by [sponsoring him on GitHub](https://github.com/sponsors/egoist).**
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ---
4
+
5
+ # rollup-plugin-esbuild
6
+
7
+ ![npm version](https://badgen.net/npm/v/rollup-plugin-esbuild) ![npm downloads](https://badgen.net/npm/dm/rollup-plugin-esbuild)
8
+
9
+ [esbuild](https://github.com/evanw/esbuild) is by far one of the fastest TS/ESNext to ES6 compilers and minifier, this plugin replaces `rollup-plugin-typescript2`, `@rollup/plugin-typescript` and `rollup-plugin-terser` for you.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ yarn add esbuild rollup-plugin-esbuild --dev
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ In `rollup.config.js`:
20
+
21
+ ```js
22
+ import esbuild from 'rollup-plugin-esbuild'
23
+
24
+ export default {
25
+ plugins: [
26
+ esbuild({
27
+ // All options are optional
28
+ include: /\.[jt]sx?$/, // default, inferred from `loaders` option
29
+ exclude: /node_modules/, // default
30
+ sourceMap: true, // default
31
+ minify: process.env.NODE_ENV === 'production',
32
+ target: 'es2017', // default, or 'es20XX', 'esnext'
33
+ jsx: 'transform', // default, or 'preserve'
34
+ jsxFactory: 'React.createElement',
35
+ jsxFragment: 'React.Fragment',
36
+ // Like @rollup/plugin-replace
37
+ define: {
38
+ __VERSION__: '"x.y.z"',
39
+ },
40
+ tsconfig: 'tsconfig.json', // default
41
+ // Add extra loaders
42
+ loaders: {
43
+ // Add .json files support
44
+ // require @rollup/plugin-commonjs
45
+ '.json': 'json',
46
+ // Enable JSX in .js files too
47
+ '.js': 'jsx',
48
+ },
49
+ }),
50
+ ],
51
+ }
52
+ ```
53
+
54
+ - `include` and `exclude` can be `String | RegExp | Array[...String|RegExp]`, when supplied it will override default values.
55
+ - It uses `jsx`, `jsxDev`, `jsxFactory`, `jsxFragmentFactory` and `target` options from your `tsconfig.json` as default values.
56
+
57
+ ### Declaration File
58
+
59
+ There are serveral ways to generate declaration file:
60
+
61
+ - Use `tsc` with `emitDeclarationOnly`, the slowest way but you get type checking, it doesn't bundle the `.d.ts` files.
62
+ - Use [`rollup-plugin-dts`](https://github.com/Swatinem/rollup-plugin-dts) which generates and bundle `.d.ts`, also does type checking.
63
+ - Use [`api-extractor`](https://api-extractor.com/) by Microsoft, looks quite complex to me so I didn't try it, PR welcome to update this section.
64
+
65
+ ### Use with Vue JSX
66
+
67
+ Use this with [rollup-plugin-vue-jsx](https://github.com/xxholly32/rollup-plugin-vue-jsx):
68
+
69
+ ```js
70
+ import vueJsx from 'rollup-plugin-vue-jsx-compat'
71
+ import esbuild from 'rollup-plugin-esbuild'
72
+
73
+ export default {
74
+ // ...
75
+ plugins: [
76
+ vueJsx(),
77
+ esbuild({
78
+ jsxFactory: 'vueJsxCompat',
79
+ }),
80
+ ],
81
+ }
82
+ ```
83
+
84
+ ### Standalone Minify Plugin
85
+
86
+ If you only want to use this plugin to minify your bundle:
87
+
88
+ ```js
89
+ import { minify } from 'rollup-plugin-esbuild'
90
+
91
+ export default {
92
+ plugins: [minify()],
93
+ }
94
+ ```
95
+
96
+ ### Optimizing Deps
97
+
98
+ You can use this plugin to pre-bundle dependencies using esbuild and inline them in the Rollup-generated bundle:
99
+
100
+ ```js
101
+ esbuild({
102
+ optimizeDeps: {
103
+ include: ['vue', 'vue-router'],
104
+ },
105
+ })
106
+ ```
107
+
108
+ This eliminates the need of `@rollup/plugin-node-modules` and `@rollup/plugin-commonjs`.
109
+
110
+ Note that this is an **experimental features**, breaking changes might happen across minor version bump.
111
+
112
+ TODO: Maybe we can scan Rollup input files to get a list of deps to optimize automatically.
113
+
114
+ ## Sponsors
115
+
116
+ [![sponsors](https://sponsors-images.egoist.sh/sponsors.svg)](https://github.com/sponsors/egoist)
117
+
118
+ ## License
119
+
120
+ MIT © [EGOIST (Kevin Titor)](https://github.com/sponsors/egoist)
@@ -0,0 +1,41 @@
1
+ import { Plugin } from 'rollup';
2
+ import { TransformOptions, BuildOptions, Loader } from '@ohos-ports/esbuild';
3
+ import { FilterPattern } from '@rollup/pluginutils';
4
+
5
+ /** Mark some properties as optional, leaving others unchanged */
6
+ declare type MarkOptional<T, K extends keyof T> = T extends T ? Omit<T, K> & Partial<Pick<T, K>> : never;
7
+
8
+ declare type Options$1 = Omit<TransformOptions, 'sourcemap'> & {
9
+ sourceMap?: boolean;
10
+ };
11
+ declare const minify: ({ sourceMap, ...options }?: Options$1) => Plugin;
12
+
13
+ declare type OptimizeDepsOptions = {
14
+ include: string[];
15
+ exclude?: string[];
16
+ cwd: string;
17
+ esbuildOptions?: BuildOptions;
18
+ sourceMap: boolean;
19
+ };
20
+
21
+ declare type Options = Omit<TransformOptions, 'sourcemap' | 'loader' | 'tsconfigRaw'> & {
22
+ include?: FilterPattern;
23
+ exclude?: FilterPattern;
24
+ sourceMap?: boolean;
25
+ optimizeDeps?: MarkOptional<OptimizeDepsOptions, 'cwd' | 'sourceMap'>;
26
+ /**
27
+ * Use this tsconfig file instead
28
+ * Disable it by setting to `false`
29
+ */
30
+ tsconfig?: string | false;
31
+ /**
32
+ * Map extension to esbuild loader
33
+ * Note that each entry (the extension) needs to start with a dot
34
+ */
35
+ loaders?: {
36
+ [ext: string]: Loader | false;
37
+ };
38
+ };
39
+ declare const _default: ({ include, exclude, sourceMap, optimizeDeps, tsconfig, loaders: _loaders, ...esbuildOptions }?: Options) => Plugin;
40
+
41
+ export { Options, _default as default, minify };
package/dist/index.js ADDED
@@ -0,0 +1,347 @@
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
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/index.ts
27
+ var src_exports = {};
28
+ __export(src_exports, {
29
+ default: () => src_default,
30
+ minify: () => minify
31
+ });
32
+ module.exports = __toCommonJS(src_exports);
33
+ var import_fs3 = require("fs");
34
+ var import_path2 = require("path");
35
+ var import_esbuild4 = require("@ohos-ports/esbuild");
36
+ var import_pluginutils = require("@rollup/pluginutils");
37
+ var import_debug = __toESM(require("debug"));
38
+
39
+ // src/options.ts
40
+ var import_fs = __toESM(require("fs"));
41
+ var import_joycon = __toESM(require("joycon"));
42
+ var import_jsonc_parser = require("jsonc-parser");
43
+ var joycon = new import_joycon.default();
44
+ joycon.addLoader({
45
+ test: /\.json$/,
46
+ load: async (file) => {
47
+ const content = await import_fs.default.promises.readFile(file, "utf8");
48
+ return (0, import_jsonc_parser.parse)(content);
49
+ }
50
+ });
51
+ var jsxValueMap = {
52
+ preserve: {
53
+ jsx: "preserve"
54
+ },
55
+ react: {
56
+ jsx: "transform"
57
+ },
58
+ "react-jsx": {
59
+ jsx: "automatic"
60
+ },
61
+ "react-jsxdev": {
62
+ jsx: "automatic",
63
+ jsxDev: true
64
+ }
65
+ };
66
+ var getOptions = async (cwd, tsconfig) => {
67
+ const { data, path: path2 } = await joycon.load([tsconfig || "tsconfig.json"], cwd);
68
+ if (path2 && data) {
69
+ const { jsxFactory, jsxFragmentFactory, target, jsx } = data.compilerOptions || {};
70
+ return {
71
+ jsxFactory,
72
+ jsxFragment: jsxFragmentFactory,
73
+ target: target && target.toLowerCase(),
74
+ ...jsxValueMap[jsx]
75
+ };
76
+ }
77
+ return {};
78
+ };
79
+
80
+ // src/minify.ts
81
+ var import_esbuild2 = require("@ohos-ports/esbuild");
82
+
83
+ // src/warn.ts
84
+ var import_esbuild = require("@ohos-ports/esbuild");
85
+ var warn = async (pluginContext, messages) => {
86
+ if (messages.length > 0) {
87
+ const warnings = await (0, import_esbuild.formatMessages)(messages, {
88
+ kind: "warning",
89
+ color: true
90
+ });
91
+ warnings.forEach((warning) => pluginContext.warn(warning));
92
+ }
93
+ };
94
+
95
+ // src/minify.ts
96
+ var getEsbuildFormat = (rollupFormat) => {
97
+ if (rollupFormat === "es") {
98
+ return "esm";
99
+ }
100
+ if (rollupFormat === "cjs") {
101
+ return rollupFormat;
102
+ }
103
+ };
104
+ var getRenderChunk = ({
105
+ sourceMap = true,
106
+ ...options
107
+ }) => async function(code, _, rollupOptions) {
108
+ if (options.minify || options.minifyWhitespace || options.minifyIdentifiers || options.minifySyntax) {
109
+ const format = getEsbuildFormat(rollupOptions.format);
110
+ const result = await (0, import_esbuild2.transform)(code, {
111
+ format,
112
+ loader: "js",
113
+ sourcemap: sourceMap,
114
+ ...options
115
+ });
116
+ await warn(this, result.warnings);
117
+ if (result.code) {
118
+ return {
119
+ code: result.code,
120
+ map: result.map || null
121
+ };
122
+ }
123
+ }
124
+ return null;
125
+ };
126
+ var minify = ({
127
+ sourceMap = true,
128
+ ...options
129
+ } = {}) => {
130
+ return {
131
+ name: "esbuild-minify",
132
+ renderChunk: getRenderChunk({
133
+ minify: true,
134
+ ...options,
135
+ sourceMap
136
+ })
137
+ };
138
+ };
139
+
140
+ // src/optimizer/optmize-deps.ts
141
+ var import_fs2 = __toESM(require("fs"));
142
+ var import_path = __toESM(require("path"));
143
+ var import_esbuild3 = require("@ohos-ports/esbuild");
144
+ var esModuleLexer = __toESM(require("es-module-lexer"));
145
+ var slash = (p) => p.replace(/\\/g, "/");
146
+ var optimizeDeps = async (options) => {
147
+ var _a;
148
+ const cacheDir = import_path.default.join(options.cwd, "node_modules/.optimize_deps");
149
+ await import_fs2.default.promises.mkdir(cacheDir, { recursive: true });
150
+ await esModuleLexer.init;
151
+ const result = await (0, import_esbuild3.build)({
152
+ entryPoints: options.include,
153
+ absWorkingDir: options.cwd,
154
+ bundle: true,
155
+ format: "esm",
156
+ ignoreAnnotations: true,
157
+ metafile: true,
158
+ splitting: true,
159
+ outdir: cacheDir,
160
+ sourcemap: options.sourceMap,
161
+ ...options.esbuildOptions,
162
+ plugins: [
163
+ {
164
+ name: "optimize-deps",
165
+ async setup(build2) {
166
+ build2.onResolve({ filter: /.*/ }, async (args) => {
167
+ var _a2, _b;
168
+ if ((_a2 = options.exclude) == null ? void 0 : _a2.includes(args.path)) {
169
+ return {
170
+ external: true
171
+ };
172
+ }
173
+ if ((_b = args.pluginData) == null ? void 0 : _b.__resolving_dep_path__) {
174
+ return;
175
+ }
176
+ if (options.include.includes(args.path)) {
177
+ const resolved = await build2.resolve(args.path, {
178
+ resolveDir: args.resolveDir,
179
+ kind: "import-statement",
180
+ pluginData: { __resolving_dep_path__: true }
181
+ });
182
+ if (resolved.errors.length > 0 || resolved.warnings.length > 0) {
183
+ return resolved;
184
+ }
185
+ return {
186
+ path: args.path,
187
+ namespace: "optimize-deps",
188
+ pluginData: {
189
+ resolveDir: args.resolveDir,
190
+ absolute: resolved.path
191
+ }
192
+ };
193
+ }
194
+ });
195
+ build2.onLoad(
196
+ { filter: /.*/, namespace: "optimize-deps" },
197
+ async (args) => {
198
+ const { absolute, resolveDir } = args.pluginData;
199
+ const contents = await import_fs2.default.promises.readFile(absolute, "utf-8");
200
+ const [, exported] = esModuleLexer.parse(contents);
201
+ return {
202
+ contents: exported.length > 0 ? `export * from '${slash(absolute)}'` : `module.exports = require('${slash(absolute)}')`,
203
+ resolveDir
204
+ };
205
+ }
206
+ );
207
+ }
208
+ },
209
+ ...((_a = options.esbuildOptions) == null ? void 0 : _a.plugins) || []
210
+ ]
211
+ });
212
+ const optimized = /* @__PURE__ */ new Map();
213
+ for (const id of options.include) {
214
+ optimized.set(id, { file: import_path.default.join(cacheDir, `${id}.js`) });
215
+ }
216
+ return {
217
+ optimized,
218
+ cacheDir
219
+ };
220
+ };
221
+
222
+ // src/index.ts
223
+ var debugOptimizeDeps = (0, import_debug.default)("rpe:optimize-deps");
224
+ var defaultLoaders = {
225
+ ".js": "js",
226
+ ".jsx": "jsx",
227
+ ".ts": "ts",
228
+ ".tsx": "tsx"
229
+ };
230
+ var src_default = ({
231
+ include,
232
+ exclude,
233
+ sourceMap = true,
234
+ optimizeDeps: optimizeDeps2,
235
+ tsconfig,
236
+ loaders: _loaders,
237
+ ...esbuildOptions
238
+ } = {}) => {
239
+ const loaders = {
240
+ ...defaultLoaders
241
+ };
242
+ if (_loaders) {
243
+ for (const key of Object.keys(_loaders)) {
244
+ const value = _loaders[key];
245
+ if (typeof value === "string") {
246
+ loaders[key] = value;
247
+ } else if (value === false) {
248
+ delete loaders[key];
249
+ }
250
+ }
251
+ }
252
+ const extensions = Object.keys(loaders);
253
+ const INCLUDE_REGEXP = new RegExp(
254
+ `\\.(${extensions.map((ext) => ext.slice(1)).join("|")})$`
255
+ );
256
+ const EXCLUDE_REGEXP = /node_modules/;
257
+ const filter = (0, import_pluginutils.createFilter)(
258
+ include || INCLUDE_REGEXP,
259
+ exclude || EXCLUDE_REGEXP
260
+ );
261
+ const resolveFile = (resolved, index = false) => {
262
+ const fileWithoutExt = resolved.replace(/\.[jt]sx?$/, "");
263
+ for (const ext of extensions) {
264
+ const file = index ? (0, import_path2.join)(resolved, `index${ext}`) : `${fileWithoutExt}${ext}`;
265
+ if ((0, import_fs3.existsSync)(file))
266
+ return file;
267
+ }
268
+ return null;
269
+ };
270
+ let optimizeDepsResult;
271
+ let cwd = process.cwd();
272
+ return {
273
+ name: "esbuild",
274
+ options({ context }) {
275
+ if (context) {
276
+ cwd = context;
277
+ }
278
+ return null;
279
+ },
280
+ async buildStart() {
281
+ if (!optimizeDeps2 || optimizeDepsResult)
282
+ return;
283
+ optimizeDepsResult = await optimizeDeps({
284
+ cwd,
285
+ sourceMap,
286
+ ...optimizeDeps2
287
+ });
288
+ debugOptimizeDeps("optimized %O", optimizeDepsResult.optimized);
289
+ },
290
+ async resolveId(id, importer) {
291
+ if (optimizeDepsResult == null ? void 0 : optimizeDepsResult.optimized.has(id)) {
292
+ const m = optimizeDepsResult.optimized.get(id);
293
+ debugOptimizeDeps("resolved %s to %s", id, m.file);
294
+ return m.file;
295
+ }
296
+ if (importer && id[0] === ".") {
297
+ const resolved = (0, import_path2.resolve)(
298
+ importer ? (0, import_path2.dirname)(importer) : process.cwd(),
299
+ id
300
+ );
301
+ let file = resolveFile(resolved);
302
+ if (file)
303
+ return file;
304
+ if (!file && (0, import_fs3.existsSync)(resolved) && (0, import_fs3.statSync)(resolved).isDirectory()) {
305
+ file = resolveFile(resolved, true);
306
+ if (file)
307
+ return file;
308
+ }
309
+ }
310
+ },
311
+ async transform(code, id) {
312
+ if (!filter(id) || (optimizeDepsResult == null ? void 0 : optimizeDepsResult.optimized.has(id))) {
313
+ return null;
314
+ }
315
+ const ext = (0, import_path2.extname)(id);
316
+ const loader = loaders[ext];
317
+ if (!loader) {
318
+ return null;
319
+ }
320
+ const defaultOptions = tsconfig === false ? {} : await getOptions((0, import_path2.dirname)(id), tsconfig);
321
+ const result = await (0, import_esbuild4.transform)(code, {
322
+ loader,
323
+ target: defaultOptions.target || "es2017",
324
+ jsxFactory: defaultOptions.jsxFactory,
325
+ jsxFragment: defaultOptions.jsxFragment,
326
+ jsx: defaultOptions.jsx,
327
+ ...defaultOptions.jsxDev ? { jsxDev: true } : {},
328
+ sourcemap: sourceMap,
329
+ sourcefile: id,
330
+ ...esbuildOptions
331
+ });
332
+ await warn(this, result.warnings);
333
+ return result.code && {
334
+ code: result.code,
335
+ map: result.map || null
336
+ };
337
+ },
338
+ renderChunk: getRenderChunk({
339
+ ...esbuildOptions,
340
+ sourceMap
341
+ })
342
+ };
343
+ };
344
+ // Annotate the CommonJS export names for ESM import in node:
345
+ 0 && (module.exports = {
346
+ minify
347
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,318 @@
1
+ // src/index.ts
2
+ import { existsSync, statSync } from "fs";
3
+ import { extname, resolve, dirname, join } from "path";
4
+ import { transform as transform2 } from "@ohos-ports/esbuild";
5
+ import { createFilter } from "@rollup/pluginutils";
6
+ import createDebug from "debug";
7
+
8
+ // src/options.ts
9
+ import fs from "fs";
10
+ import JoyCon from "joycon";
11
+ import { parse } from "jsonc-parser";
12
+ var joycon = new JoyCon();
13
+ joycon.addLoader({
14
+ test: /\.json$/,
15
+ load: async (file) => {
16
+ const content = await fs.promises.readFile(file, "utf8");
17
+ return parse(content);
18
+ }
19
+ });
20
+ var jsxValueMap = {
21
+ preserve: {
22
+ jsx: "preserve"
23
+ },
24
+ react: {
25
+ jsx: "transform"
26
+ },
27
+ "react-jsx": {
28
+ jsx: "automatic"
29
+ },
30
+ "react-jsxdev": {
31
+ jsx: "automatic",
32
+ jsxDev: true
33
+ }
34
+ };
35
+ var getOptions = async (cwd, tsconfig) => {
36
+ const { data, path: path2 } = await joycon.load([tsconfig || "tsconfig.json"], cwd);
37
+ if (path2 && data) {
38
+ const { jsxFactory, jsxFragmentFactory, target, jsx } = data.compilerOptions || {};
39
+ return {
40
+ jsxFactory,
41
+ jsxFragment: jsxFragmentFactory,
42
+ target: target && target.toLowerCase(),
43
+ ...jsxValueMap[jsx]
44
+ };
45
+ }
46
+ return {};
47
+ };
48
+
49
+ // src/minify.ts
50
+ import { transform } from "@ohos-ports/esbuild";
51
+
52
+ // src/warn.ts
53
+ import {
54
+ formatMessages
55
+ } from "@ohos-ports/esbuild";
56
+ var warn = async (pluginContext, messages) => {
57
+ if (messages.length > 0) {
58
+ const warnings = await formatMessages(messages, {
59
+ kind: "warning",
60
+ color: true
61
+ });
62
+ warnings.forEach((warning) => pluginContext.warn(warning));
63
+ }
64
+ };
65
+
66
+ // src/minify.ts
67
+ var getEsbuildFormat = (rollupFormat) => {
68
+ if (rollupFormat === "es") {
69
+ return "esm";
70
+ }
71
+ if (rollupFormat === "cjs") {
72
+ return rollupFormat;
73
+ }
74
+ };
75
+ var getRenderChunk = ({
76
+ sourceMap = true,
77
+ ...options
78
+ }) => async function(code, _, rollupOptions) {
79
+ if (options.minify || options.minifyWhitespace || options.minifyIdentifiers || options.minifySyntax) {
80
+ const format = getEsbuildFormat(rollupOptions.format);
81
+ const result = await transform(code, {
82
+ format,
83
+ loader: "js",
84
+ sourcemap: sourceMap,
85
+ ...options
86
+ });
87
+ await warn(this, result.warnings);
88
+ if (result.code) {
89
+ return {
90
+ code: result.code,
91
+ map: result.map || null
92
+ };
93
+ }
94
+ }
95
+ return null;
96
+ };
97
+ var minify = ({
98
+ sourceMap = true,
99
+ ...options
100
+ } = {}) => {
101
+ return {
102
+ name: "esbuild-minify",
103
+ renderChunk: getRenderChunk({
104
+ minify: true,
105
+ ...options,
106
+ sourceMap
107
+ })
108
+ };
109
+ };
110
+
111
+ // src/optimizer/optmize-deps.ts
112
+ import fs2 from "fs";
113
+ import path from "path";
114
+ import { build } from "@ohos-ports/esbuild";
115
+ import * as esModuleLexer from "es-module-lexer";
116
+ var slash = (p) => p.replace(/\\/g, "/");
117
+ var optimizeDeps = async (options) => {
118
+ var _a;
119
+ const cacheDir = path.join(options.cwd, "node_modules/.optimize_deps");
120
+ await fs2.promises.mkdir(cacheDir, { recursive: true });
121
+ await esModuleLexer.init;
122
+ const result = await build({
123
+ entryPoints: options.include,
124
+ absWorkingDir: options.cwd,
125
+ bundle: true,
126
+ format: "esm",
127
+ ignoreAnnotations: true,
128
+ metafile: true,
129
+ splitting: true,
130
+ outdir: cacheDir,
131
+ sourcemap: options.sourceMap,
132
+ ...options.esbuildOptions,
133
+ plugins: [
134
+ {
135
+ name: "optimize-deps",
136
+ async setup(build2) {
137
+ build2.onResolve({ filter: /.*/ }, async (args) => {
138
+ var _a2, _b;
139
+ if ((_a2 = options.exclude) == null ? void 0 : _a2.includes(args.path)) {
140
+ return {
141
+ external: true
142
+ };
143
+ }
144
+ if ((_b = args.pluginData) == null ? void 0 : _b.__resolving_dep_path__) {
145
+ return;
146
+ }
147
+ if (options.include.includes(args.path)) {
148
+ const resolved = await build2.resolve(args.path, {
149
+ resolveDir: args.resolveDir,
150
+ kind: "import-statement",
151
+ pluginData: { __resolving_dep_path__: true }
152
+ });
153
+ if (resolved.errors.length > 0 || resolved.warnings.length > 0) {
154
+ return resolved;
155
+ }
156
+ return {
157
+ path: args.path,
158
+ namespace: "optimize-deps",
159
+ pluginData: {
160
+ resolveDir: args.resolveDir,
161
+ absolute: resolved.path
162
+ }
163
+ };
164
+ }
165
+ });
166
+ build2.onLoad(
167
+ { filter: /.*/, namespace: "optimize-deps" },
168
+ async (args) => {
169
+ const { absolute, resolveDir } = args.pluginData;
170
+ const contents = await fs2.promises.readFile(absolute, "utf-8");
171
+ const [, exported] = esModuleLexer.parse(contents);
172
+ return {
173
+ contents: exported.length > 0 ? `export * from '${slash(absolute)}'` : `module.exports = require('${slash(absolute)}')`,
174
+ resolveDir
175
+ };
176
+ }
177
+ );
178
+ }
179
+ },
180
+ ...((_a = options.esbuildOptions) == null ? void 0 : _a.plugins) || []
181
+ ]
182
+ });
183
+ const optimized = /* @__PURE__ */ new Map();
184
+ for (const id of options.include) {
185
+ optimized.set(id, { file: path.join(cacheDir, `${id}.js`) });
186
+ }
187
+ return {
188
+ optimized,
189
+ cacheDir
190
+ };
191
+ };
192
+
193
+ // src/index.ts
194
+ var debugOptimizeDeps = createDebug("rpe:optimize-deps");
195
+ var defaultLoaders = {
196
+ ".js": "js",
197
+ ".jsx": "jsx",
198
+ ".ts": "ts",
199
+ ".tsx": "tsx"
200
+ };
201
+ var src_default = ({
202
+ include,
203
+ exclude,
204
+ sourceMap = true,
205
+ optimizeDeps: optimizeDeps2,
206
+ tsconfig,
207
+ loaders: _loaders,
208
+ ...esbuildOptions
209
+ } = {}) => {
210
+ const loaders = {
211
+ ...defaultLoaders
212
+ };
213
+ if (_loaders) {
214
+ for (const key of Object.keys(_loaders)) {
215
+ const value = _loaders[key];
216
+ if (typeof value === "string") {
217
+ loaders[key] = value;
218
+ } else if (value === false) {
219
+ delete loaders[key];
220
+ }
221
+ }
222
+ }
223
+ const extensions = Object.keys(loaders);
224
+ const INCLUDE_REGEXP = new RegExp(
225
+ `\\.(${extensions.map((ext) => ext.slice(1)).join("|")})$`
226
+ );
227
+ const EXCLUDE_REGEXP = /node_modules/;
228
+ const filter = createFilter(
229
+ include || INCLUDE_REGEXP,
230
+ exclude || EXCLUDE_REGEXP
231
+ );
232
+ const resolveFile = (resolved, index = false) => {
233
+ const fileWithoutExt = resolved.replace(/\.[jt]sx?$/, "");
234
+ for (const ext of extensions) {
235
+ const file = index ? join(resolved, `index${ext}`) : `${fileWithoutExt}${ext}`;
236
+ if (existsSync(file))
237
+ return file;
238
+ }
239
+ return null;
240
+ };
241
+ let optimizeDepsResult;
242
+ let cwd = process.cwd();
243
+ return {
244
+ name: "esbuild",
245
+ options({ context }) {
246
+ if (context) {
247
+ cwd = context;
248
+ }
249
+ return null;
250
+ },
251
+ async buildStart() {
252
+ if (!optimizeDeps2 || optimizeDepsResult)
253
+ return;
254
+ optimizeDepsResult = await optimizeDeps({
255
+ cwd,
256
+ sourceMap,
257
+ ...optimizeDeps2
258
+ });
259
+ debugOptimizeDeps("optimized %O", optimizeDepsResult.optimized);
260
+ },
261
+ async resolveId(id, importer) {
262
+ if (optimizeDepsResult == null ? void 0 : optimizeDepsResult.optimized.has(id)) {
263
+ const m = optimizeDepsResult.optimized.get(id);
264
+ debugOptimizeDeps("resolved %s to %s", id, m.file);
265
+ return m.file;
266
+ }
267
+ if (importer && id[0] === ".") {
268
+ const resolved = resolve(
269
+ importer ? dirname(importer) : process.cwd(),
270
+ id
271
+ );
272
+ let file = resolveFile(resolved);
273
+ if (file)
274
+ return file;
275
+ if (!file && existsSync(resolved) && statSync(resolved).isDirectory()) {
276
+ file = resolveFile(resolved, true);
277
+ if (file)
278
+ return file;
279
+ }
280
+ }
281
+ },
282
+ async transform(code, id) {
283
+ if (!filter(id) || (optimizeDepsResult == null ? void 0 : optimizeDepsResult.optimized.has(id))) {
284
+ return null;
285
+ }
286
+ const ext = extname(id);
287
+ const loader = loaders[ext];
288
+ if (!loader) {
289
+ return null;
290
+ }
291
+ const defaultOptions = tsconfig === false ? {} : await getOptions(dirname(id), tsconfig);
292
+ const result = await transform2(code, {
293
+ loader,
294
+ target: defaultOptions.target || "es2017",
295
+ jsxFactory: defaultOptions.jsxFactory,
296
+ jsxFragment: defaultOptions.jsxFragment,
297
+ jsx: defaultOptions.jsx,
298
+ ...defaultOptions.jsxDev ? { jsxDev: true } : {},
299
+ sourcemap: sourceMap,
300
+ sourcefile: id,
301
+ ...esbuildOptions
302
+ });
303
+ await warn(this, result.warnings);
304
+ return result.code && {
305
+ code: result.code,
306
+ map: result.map || null
307
+ };
308
+ },
309
+ renderChunk: getRenderChunk({
310
+ ...esbuildOptions,
311
+ sourceMap
312
+ })
313
+ };
314
+ };
315
+ export {
316
+ src_default as default,
317
+ minify
318
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@ohos-ports/rollup-plugin-esbuild",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "5.0.0-beta.1",
4
+ "main": "dist/index.js",
5
+ "module": "dist/index.mjs",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.mjs",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "author": "EGOIST",
13
+ "license": "MIT",
14
+ "repository": "https://github.com/egoist/rollup-plugin-esbuild",
15
+ "scripts": {
16
+ "test": "jest",
17
+ "example:rollup-node-resolve": "rollup --bundleConfigAsCjs -c example/rollup.config.js",
18
+ "example:esbuild-optimize-deps": "OPTIMIZE=true rollup --bundleConfigAsCjs -c example/rollup.config.js",
19
+ "build": "rm -rf dist && tsup src/index.ts --format esm,cjs --dts-resolve",
20
+ "prepublishOnly": "npm run build"
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "devDependencies": {
26
+ "@rollup/plugin-commonjs": "^23.0.0",
27
+ "@rollup/plugin-node-resolve": "^15.0.0",
28
+ "@types/debug": "^4.1.7",
29
+ "@types/jest": "^29.1.2",
30
+ "@types/node": "16.11.66",
31
+ "esbuild": "^0.15.11",
32
+ "istextorbinary": "^6.0.0",
33
+ "jest": "^29.2.0",
34
+ "lodash": "^4.17.21",
35
+ "prettier": "^2.7.1",
36
+ "react": "^18.2.0",
37
+ "rollup": "^3.2.2",
38
+ "three": "^0.145.0",
39
+ "ts-essentials": "^9.3.0",
40
+ "ts-jest": "^29.0.3",
41
+ "tsup": "^6.3.0",
42
+ "typescript": "^4.8.4",
43
+ "vue": "^3.2.41"
44
+ },
45
+ "dependencies": {
46
+ "@rollup/pluginutils": "^5.0.1",
47
+ "debug": "^4.3.4",
48
+ "es-module-lexer": "^1.0.5",
49
+ "joycon": "^3.1.1",
50
+ "jsonc-parser": "^3.2.0"
51
+ },
52
+ "peerDependencies": {
53
+ "@ohos-ports/esbuild": ">=0.10.1 || 0.17.18-beta.0",
54
+ "rollup": "^1.20.0 || ^2.0.0 || ^3.0.0"
55
+ },
56
+ "engines": {
57
+ "node": ">=14.18.0",
58
+ "npm": ">=8.0.0"
59
+ },
60
+ "description": "Simple rollup plugin for esbuild (ohos-ports port: esbuild peer satisfied by @ohos-ports/esbuild)"
61
+ }