bunchee 3.0.0-beta.10 → 3.0.0-beta.12

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/README.md CHANGED
@@ -22,31 +22,19 @@ npm install --save-dev bunchee
22
22
  ```
23
23
 
24
24
  ## Usage
25
- ### Package.json Configuration
26
25
 
27
- Declare the main and module fields in your package.json file, then call the bunchee CLI in the build scripts. If you are using TypeScript, types will be generated automatically based on the typings or types field in your package.json file.
26
+ Create your library
28
27
 
29
- #### Configure `main` and `module` fields
30
-
31
- You can have Commonjs + ESModules output as the simple config
32
-
33
- ```json
34
- {
35
- "main": "dist/pkg.cjs.js",
36
- "module": "dist/pkg.esm.js",
37
- "scripts": {
38
- "build": "bunchee ./src/index.js"
39
- },
40
- "types": "dist/types/index.d.ts"
41
- }
28
+ ```sh
29
+ cd ./my-lib && mkdir src
30
+ touch ./src/index.js
31
+ touch package.json
42
32
  ```
43
-
44
- #### Configure `exports` field
33
+ Configure module exports
45
34
 
46
35
  [exports sugar in Node.js](https://nodejs.org/api/packages.html#exports-sugar)
47
36
 
48
- You can use the exports field to support different conditions and leverage the same functionality as other bundlers, such as webpack. The exports field allows you to define multiple conditions.
49
-
37
+ You can use the `exports` field to support different conditions and leverage the same functionality as other bundlers, such as webpack. The exports field allows you to define multiple conditions.
50
38
 
51
39
  ```json
52
40
  {
@@ -56,102 +44,96 @@ You can use the exports field to support different conditions and leverage the s
56
44
  "module": "dist/index.esm.js"
57
45
  },
58
46
  "scripts": {
59
- "build": "bunchee ./src/index.js"
47
+ "build": "bunchee"
60
48
  },
61
49
  }
62
50
  ```
63
51
 
64
- ### CLI
52
+ Using pure ESM package?
65
53
 
54
+ ```json
55
+ {
56
+ "type": "module",
57
+ "main": "./dist/index.js",
58
+ "scripts": {
59
+ "build": "bunchee"
60
+ }
61
+ }
66
62
  ```
67
- Usage: bunchee [options]
68
-
69
- Options:
70
- -v, --version output the version number
71
- -w, --watch watch src files changes
72
- -m, --minify compress output. default: false
73
- -o, --output <file> specify output filename
74
- -f, --format <format> type of output (esm, amd, cjs, iife, umd, system), default: esm
75
- -e, --external <mod> specify an external dependency
76
- -h, --help output usage information
77
- --target <target> js features target: swc target es versions. default: es2015
78
- --runtime <runtime> build runtime (nodejs, browser). default: browser
79
- --cwd <cwd> specify current working directory
80
- --sourcemap enable sourcemap generation, default: false
81
- --dts determine if need to generate types, default: false
82
-
83
- Usage:
84
- $ bunchee ./src/index.js # if you set main fields in package.json
85
- $ bunchee ./src/index.ts -o ./dist/bundle.js # specify the dist file path
86
- ```
87
63
 
88
- Run bunchee via CLI
64
+ Then just run `npm run build`, or `pnpm build` / `yarn build` if you're using these package managers.
65
+
66
+ ## Configuration
67
+
68
+ `bunchee` CLI provides few options to create different bundles or generating types.
69
+
70
+ ### CLI Options
71
+
72
+ - Output (`-o <file>`): Specify output filename.
73
+ - Format (`-f <format>`): Set output format (default: `'esm'`).
74
+ - External (`--external <dep,>`): Specifying extra external dependencies, by default it is the list of `dependencies` and `peerDependencies` from `package.json`. Values are separate by comma.
75
+ - Target (`--target <target>`): Set ECMAScript target (default: `'es2016'`).
76
+ - Runtime (`--runtime <runtime>`): Set build runtime (default: `'browser'`).
77
+ - Environment (`--env <env,>`): Define environment variables. (default: `NODE_ENV`, separate by comma)
78
+ - Working Directory (`--cwd <cwd>`): Set current working directory where containing `package.json`.
79
+ - Types only (`--dts`): Generate TypeScript declaration files without assets.
80
+ - Minify (`-m`): Compress output.
81
+ - Watch (`-w`): Watch for source file changes.
82
+
83
+ ### Basic Example
89
84
 
90
85
  ```sh
91
86
  cd <project-root-dir>
92
- bunchee ./src/index.js -f cjs -o ./dist/bundle.js
93
87
 
88
+ # specifying input, output and format
89
+
90
+ bunchee ./src/index.js -f cjs -o ./dist/bundle.js
94
91
  bunchee ./src/index.js -f esm -o ./dist/bundle.esm.js
95
- # if you don't specify format type, default format is ESModule
96
- # bunchee ./src/index.js -o ./dist/bundle.esm.js
92
+
93
+ # build node.js library, or change target to es2019
94
+ bunchee ./src/index.js --runtime node --target es2019
97
95
  ```
98
96
 
99
- ### Node.js API
97
+ #### Specifying extra external dependencies
100
98
 
101
- ```js
102
- import path from 'path'
103
- import { bundle } from 'bunchee'
99
+ If you want to mark specific dependencies as external and not include them in the bundle, use the `--external` option followed by a comma-separated list of dependency names:
104
100
 
105
- // The definition of these options can be found in help information
106
- await bundle(path.resolve('./src/index.ts'), {
107
- dts: false,
108
- watch: false,
109
- minify: false,
110
- sourcemap: false,
111
- external: [],
112
- format: 'esm',
113
- target: 'es2016',
114
- runtime: 'nodejs',
115
- })
101
+ ```sh
102
+ bunchee --external=dependency1,dependency2,dependency3
116
103
  ```
117
104
 
118
- #### Watch Mode
119
-
120
- Bunchee offers a convenient watch mode for rebuilding your library whenever changes are made to the source files. To enable this feature, use either -w or --watch.
105
+ Replace `dependency1`, `dependency2`, and `dependency3` with the names of the dependencies you want to exclude from the bundle.
121
106
 
122
- ### Typescript
123
-
124
- By default bunchee includes Typescript v3.9.x inside as a dependency. If you want to use your own version, just install typescript as another dev dependency then bunchee will automatically pick it.
107
+ #### Bundling everything without external dependencies
108
+ To bundle your library without external dependencies, use the `--no-external` option:
125
109
 
126
110
  ```sh
127
- yarn add -D bunchee typescript
111
+ bunchee --no-external
128
112
  ```
113
+ This will include all dependencies within your output bundle.
129
114
 
130
- Create `tsconfig.json` to specify any compiler options for TypeScript.
131
-
132
- This library requires at least [TypeScript 3.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html).
133
-
115
+ ### Environment Variables
116
+ To pass environment variables to your bundled code, use the --env option followed by a comma-separated list of environment variable names:
134
117
 
135
- #### `target`
118
+ ```bash
119
+ bunchee --env=ENV1,ENV2,ENV3
120
+ ```
136
121
 
137
- If you specify `target` option in `tsconfig.json`, then you don't have to pass it again through CLI.
122
+ Replace `ENV1`, `ENV2`, and `ENV3` with the names of the environment variables you want to include in your bundled code. These environment variables will be inlined during the bundling process.
138
123
 
139
- ## Advanced
140
124
 
141
- ### Multiple Exports
125
+ ### Entry Files Convention
142
126
 
143
127
  While `exports` filed is becoming the standard of exporting in node.js, bunchee also supports to build multiple exports all in one command.
144
128
 
145
129
  What you need to do is just add an entry file with the name (`[name].[ext]`) that matches the exported name from exports field in package.json. For instance:
146
130
 
147
- * `index.ts` will match `"."` export name or the if there's only one main export.
148
- * `lite.ts` will match `"./lite"` export name.
131
+ * `<cwd>/src/index.ts` will match `"."` export name or the if there's only one main export.
132
+ * `<cwd>/src/lite.ts` will match `"./lite"` export name.
149
133
 
150
134
  The build script will be simplified to just `bunchee` in package.json without configure any input sources for each exports. Of course you can still specify other arguments as you need.
151
135
 
152
- #### How it works
153
-
154
- Assuming you have main entry export `"."` and subpath export `"./lite"` with different exports condition listed in package.json
136
+ Assuming you have default export package as `"."` and subpath export `"./lite"` with different exports condition listed in package.json
155
137
 
156
138
  ```json
157
139
  {
@@ -172,13 +154,66 @@ Assuming you have main entry export `"."` and subpath export `"./lite"` with dif
172
154
  Then you need to add two entry files `index.ts` and `lite.ts` in project root directory to match the export name `"."` and `"./lite"`, bunchee will associate these entry files with export names then use them as input source and output paths information.
173
155
 
174
156
  ```
175
- - example/
176
- |- lite.ts
177
- |- index.ts
157
+ - my-lib/
178
158
  |- src/
159
+ |- lite.ts
160
+ |- index.ts
179
161
  |- package.json
180
162
  ```
181
163
 
164
+ #### Package lint
165
+
166
+ `bunchee` has support for checking the package bundles are matched with package exports configuration.
167
+
168
+ ### TypeScript
169
+
170
+ By default bunchee includes Typescript v3.9.x inside as a dependency. If you want to use your own version, just install typescript as another dev dependency then bunchee will automatically pick it.
171
+
172
+ ```sh
173
+ yarn add -D bunchee typescript
174
+ ```
175
+
176
+ Create `tsconfig.json` to specify any compiler options for TypeScript.
177
+
178
+ This library requires at least [TypeScript 3.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html).
179
+
180
+
181
+ Adding `"types"` or `"typing"` field in your package.json, types will be generated with that path.
182
+
183
+ ```json
184
+ {
185
+ "types": "dist/types/index.d.ts"
186
+ }
187
+ ```
188
+
189
+ ### Node.js API
190
+
191
+ ```ts
192
+ import path from 'path'
193
+ import { bundle, type BundleConfig } from 'bunchee'
194
+
195
+ // The definition of these options can be found in help information
196
+ await bundle(path.resolve('./src/index.ts'), {
197
+ dts: false, // Boolean
198
+ watch: false, // Boolean
199
+ minify: false, // Boolean
200
+ sourcemap: false, // Boolean
201
+ external: [], // string[]
202
+ format: 'esm', // 'esm' | 'cjs'
203
+ target: 'es2016', // ES syntax target
204
+ runtime: 'nodejs', // 'browser' | 'nodejs'
205
+ cwd: process.cwd(), // string
206
+ })
207
+ ```
208
+
209
+ #### Watch Mode
210
+
211
+ Bunchee offers a convenient watch mode for rebuilding your library whenever changes are made to the source files. To enable this feature, use either -w or --watch.
212
+
213
+ #### `target`
214
+
215
+ If you specify `target` option in `tsconfig.json`, then you don't have to pass it again through CLI.
216
+
182
217
  ### License
183
218
 
184
219
  MIT
package/dist/cli.js CHANGED
@@ -1,13 +1,58 @@
1
1
  #!/usr/bin/env node
2
2
  var path = require('path');
3
3
  var arg = require('arg');
4
- require('fs');
4
+ var fs = require('fs/promises');
5
5
 
6
+ function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
7
+ try {
8
+ var info = gen[key](arg);
9
+ var value = info.value;
10
+ } catch (error) {
11
+ reject(error);
12
+ return;
13
+ }
14
+ if (info.done) {
15
+ resolve(value);
16
+ } else {
17
+ Promise.resolve(value).then(_next, _throw);
18
+ }
19
+ }
20
+ function _async_to_generator$1(fn) {
21
+ return function() {
22
+ var self = this, args = arguments;
23
+ return new Promise(function(resolve, reject) {
24
+ var gen = fn.apply(self, args);
25
+ function _next(value) {
26
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
27
+ }
28
+ function _throw(err) {
29
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
30
+ }
31
+ _next(undefined);
32
+ });
33
+ };
34
+ }
6
35
  function exit(err) {
7
36
  logger.error(err);
8
37
  process.exit(1);
9
38
  }
10
39
  const formatDuration = (duration)=>duration >= 1000 ? `${duration / 1000}s` : `${duration}ms`;
40
+ function getPackageMeta(cwd) {
41
+ return _getPackageMeta.apply(this, arguments);
42
+ }
43
+ function _getPackageMeta() {
44
+ _getPackageMeta = _async_to_generator$1(function*(cwd) {
45
+ const pkgFilePath = path.resolve(cwd, 'package.json');
46
+ let targetPackageJson = {};
47
+ try {
48
+ targetPackageJson = JSON.parse((yield fs.readFile(pkgFilePath, {
49
+ encoding: 'utf-8'
50
+ })));
51
+ } catch (_) {}
52
+ return targetPackageJson;
53
+ });
54
+ return _getPackageMeta.apply(this, arguments);
55
+ }
11
56
  const logger = {
12
57
  log (arg) {
13
58
  console.log(arg);
@@ -20,7 +65,7 @@ const logger = {
20
65
  }
21
66
  };
22
67
 
23
- var version = "3.0.0-beta.10";
68
+ var version = "3.0.0-beta.12";
24
69
 
25
70
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
26
71
  try {
@@ -36,7 +81,7 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
36
81
  Promise.resolve(value).then(_next, _throw);
37
82
  }
38
83
  }
39
- function _asyncToGenerator(fn) {
84
+ function _async_to_generator(fn) {
40
85
  return function() {
41
86
  var self = this, args = arguments;
42
87
  return new Promise(function(resolve, reject) {
@@ -60,10 +105,12 @@ Options:
60
105
  -m, --minify compress output. default: false
61
106
  -o, --output <file> specify output filename
62
107
  -f, --format <format> type of output (esm, amd, cjs, iife, umd, system), default: esm
63
- -e, --external <mod> specify an external dependency
64
108
  -h, --help output usage information
65
- --target <target> js features target: swc target es versions. default: es2015
109
+ --external <mod> specify an external dependency, separate by comma
110
+ --no-external do not bundle external dependencies
111
+ --target <target> js features target: swc target es versions. default: es2016
66
112
  --runtime <runtime> build runtime (nodejs, browser). default: browser
113
+ --env <env> inlined process env variables, separate by comma. default: NODE_ENV
67
114
  --cwd <cwd> specify current working directory
68
115
  --sourcemap enable sourcemap generation, default: false
69
116
  --dts determine if need to generate types, default: false
@@ -71,6 +118,24 @@ Options:
71
118
  function help() {
72
119
  logger.log(helpMessage);
73
120
  }
121
+ function lintPackage(cwd) {
122
+ return _lintPackage.apply(this, arguments);
123
+ }
124
+ function _lintPackage() {
125
+ _lintPackage = _async_to_generator(function*(cwd) {
126
+ const { publint } = yield import('publint');
127
+ const { printMessage } = yield import('publint/utils');
128
+ const messages = yield publint({
129
+ pkgDir: cwd,
130
+ level: 'error'
131
+ });
132
+ const pkg = yield getPackageMeta(cwd);
133
+ for (const message of messages){
134
+ console.log(printMessage(message, pkg));
135
+ }
136
+ });
137
+ return _lintPackage.apply(this, arguments);
138
+ }
74
139
  function parseCliArgs(argv) {
75
140
  let args;
76
141
  args = arg({
@@ -85,16 +150,15 @@ function parseCliArgs(argv) {
85
150
  '--runtime': String,
86
151
  '--target': String,
87
152
  '--sourcemap': Boolean,
88
- '--external': [
89
- String
90
- ],
153
+ '--env': String,
154
+ '--external': String,
155
+ '--no-external': Boolean,
91
156
  '-h': '--help',
92
157
  '-v': '--version',
93
158
  '-w': '--watch',
94
159
  '-o': '--output',
95
160
  '-f': '--format',
96
- '-m': '--minify',
97
- '-e': '--external'
161
+ '-m': '--minify'
98
162
  }, {
99
163
  permissive: true,
100
164
  argv
@@ -113,7 +177,8 @@ function parseCliArgs(argv) {
113
177
  version: args['--version'],
114
178
  runtime: args['--runtime'],
115
179
  target: args['--target'],
116
- external: args['--external']
180
+ external: !!args['--no-external'] ? null : args['--external'],
181
+ env: args['--env']
117
182
  };
118
183
  return parsedArgs;
119
184
  }
@@ -121,21 +186,23 @@ function run(args) {
121
186
  return _run.apply(this, arguments);
122
187
  }
123
188
  function _run() {
124
- _run = _asyncToGenerator(function*(args) {
125
- const { source , format , watch , minify , sourcemap , target , runtime , dts } = args;
189
+ _run = _async_to_generator(function*(args) {
190
+ var _args_external;
191
+ const { source , format , watch , minify , sourcemap , target , runtime , dts , env } = args;
126
192
  const cwd = args.cwd || process.cwd();
127
193
  const file = args.file ? path.resolve(cwd, args.file) : undefined;
128
- const cliArgs = {
194
+ const bundleConfig = {
129
195
  dts,
130
196
  file,
131
197
  format,
132
198
  cwd,
133
199
  target,
134
200
  runtime,
135
- external: args.external || [],
201
+ external: ((_args_external = args.external) == null ? void 0 : _args_external.split(',')) || [],
136
202
  watch: !!watch,
137
203
  minify: !!minify,
138
- sourcemap: sourcemap === false ? false : true
204
+ sourcemap: sourcemap === false ? false : true,
205
+ env: (env == null ? void 0 : env.split(',')) || []
139
206
  };
140
207
  if (args.version) {
141
208
  return logger.log(version);
@@ -144,11 +211,11 @@ function _run() {
144
211
  return help();
145
212
  }
146
213
  const entry = source ? path.resolve(cwd, source) : '';
147
- const { bundle } = require('./lib');
214
+ const bundle = require('./index').bundle;
148
215
  let timeStart = Date.now();
149
216
  let timeEnd;
150
217
  try {
151
- yield bundle(entry, cliArgs);
218
+ yield bundle(entry, bundleConfig);
152
219
  timeEnd = Date.now();
153
220
  } catch (err) {
154
221
  if (err.name === 'NOT_EXISTED') {
@@ -158,9 +225,14 @@ function _run() {
158
225
  throw err;
159
226
  }
160
227
  const duration = timeEnd - timeStart;
161
- if (!watch) {
162
- logger.log(`✨ Finished in ${formatDuration(duration)}`);
228
+ // watching mode
229
+ if (watch) {
230
+ logger.log(`🔍 Watching assets in ${cwd}...`);
231
+ return;
163
232
  }
233
+ // build mode
234
+ logger.log(`✨ Finished in ${formatDuration(duration)}`);
235
+ yield lintPackage(cwd);
164
236
  });
165
237
  return _run.apply(this, arguments);
166
238
  }
@@ -168,7 +240,7 @@ function main() {
168
240
  return _main.apply(this, arguments);
169
241
  }
170
242
  function _main() {
171
- _main = _asyncToGenerator(function*() {
243
+ _main = _async_to_generator(function*() {
172
244
  let params, error;
173
245
  try {
174
246
  params = parseCliArgs(process.argv.slice(2));
@@ -1,13 +1,19 @@
1
1
  import { JscTarget } from '@swc/core';
2
- import { RollupOptions, InputOptions, OutputOptions } from 'rollup';
2
+ import { OutputOptions } from 'rollup';
3
3
 
4
4
  type ExportType = 'require' | 'export' | 'default' | string;
5
- type CommonConfig = {
6
- dts?: boolean;
5
+ type BundleConfig = {
6
+ file?: string;
7
+ cwd?: string;
8
+ watch?: boolean;
9
+ target?: JscTarget;
7
10
  format?: OutputOptions['format'];
8
11
  minify?: boolean;
9
12
  sourcemap?: boolean;
10
13
  external?: string[];
14
+ noExternal?: boolean;
15
+ env?: string[];
16
+ dts?: boolean;
11
17
  runtime?: string;
12
18
  exportCondition?: {
13
19
  source: string;
@@ -16,19 +22,7 @@ type CommonConfig = {
16
22
  };
17
23
  };
18
24
  type ExportCondition = string | Record<ExportType, string>;
19
- type BuncheeRollupConfig = Partial<Omit<RollupOptions, 'input' | 'output'>> & {
20
- exportName?: string;
21
- input: InputOptions;
22
- output: OutputOptions[];
23
- dtsOnly: boolean;
24
- };
25
- type CliArgs = CommonConfig & {
26
- file?: string;
27
- watch?: boolean;
28
- cwd?: string;
29
- target?: JscTarget;
30
- };
31
25
 
32
- declare function bundle(entryPath: string, { cwd, ...options }?: CliArgs): Promise<any>;
26
+ declare function bundle(entryPath: string, { cwd, ...options }?: BundleConfig): Promise<any>;
33
27
 
34
- export { BuncheeRollupConfig, CliArgs, bundle };
28
+ export { BundleConfig, bundle };
@@ -1,14 +1,16 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
 
3
- var fs = require('fs');
3
+ var fs = require('fs/promises');
4
4
  var path = require('path');
5
5
  var rollup = require('rollup');
6
+ var fs$1 = require('fs');
6
7
  var module$1 = require('module');
7
8
  var rollupPluginSwc3 = require('rollup-plugin-swc3');
8
9
  var commonjs = require('@rollup/plugin-commonjs');
9
10
  var shebang = require('rollup-plugin-preserve-shebang');
10
11
  var json = require('@rollup/plugin-json');
11
12
  var pluginNodeResolve = require('@rollup/plugin-node-resolve');
13
+ var replace = require('@rollup/plugin-replace');
12
14
 
13
15
  const rootDir = process.cwd();
14
16
  var config = {
@@ -134,20 +136,55 @@ function getExportConditionDist(pkg, exportCondition) {
134
136
  return dist;
135
137
  }
136
138
 
139
+ function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
140
+ try {
141
+ var info = gen[key](arg);
142
+ var value = info.value;
143
+ } catch (error) {
144
+ reject(error);
145
+ return;
146
+ }
147
+ if (info.done) {
148
+ resolve(value);
149
+ } else {
150
+ Promise.resolve(value).then(_next, _throw);
151
+ }
152
+ }
153
+ function _async_to_generator$1(fn) {
154
+ return function() {
155
+ var self = this, args = arguments;
156
+ return new Promise(function(resolve, reject) {
157
+ var gen = fn.apply(self, args);
158
+ function _next(value) {
159
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
160
+ }
161
+ function _throw(err) {
162
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
163
+ }
164
+ _next(undefined);
165
+ });
166
+ };
167
+ }
137
168
  function exit(err) {
138
169
  logger.error(err);
139
170
  process.exit(1);
140
171
  }
141
172
  const formatDuration = (duration)=>duration >= 1000 ? `${duration / 1000}s` : `${duration}ms`;
142
173
  function getPackageMeta(cwd) {
143
- const pkgFilePath = path.resolve(cwd, 'package.json');
144
- let targetPackageJson = {};
145
- try {
146
- targetPackageJson = JSON.parse(fs.readFileSync(pkgFilePath, {
147
- encoding: 'utf-8'
148
- }));
149
- } catch (_) {}
150
- return targetPackageJson;
174
+ return _getPackageMeta.apply(this, arguments);
175
+ }
176
+ function _getPackageMeta() {
177
+ _getPackageMeta = _async_to_generator$1(function*(cwd) {
178
+ const pkgFilePath = path.resolve(cwd, 'package.json');
179
+ let targetPackageJson = {};
180
+ try {
181
+ targetPackageJson = JSON.parse((yield fs.readFile(pkgFilePath, {
182
+ encoding: 'utf-8'
183
+ })));
184
+ } catch (_) {}
185
+ return targetPackageJson;
186
+ });
187
+ return _getPackageMeta.apply(this, arguments);
151
188
  }
152
189
  const logger = {
153
190
  log (arg) {
@@ -164,6 +201,23 @@ function isTypescript(filename) {
164
201
  const ext = path.extname(filename);
165
202
  return ext === '.ts' || ext === '.tsx';
166
203
  }
204
+ function fileExists(filePath) {
205
+ return _fileExists.apply(this, arguments);
206
+ }
207
+ function _fileExists() {
208
+ _fileExists = _async_to_generator$1(function*(filePath) {
209
+ try {
210
+ yield fs.access(filePath);
211
+ return true;
212
+ } catch (err) {
213
+ if (err.code === 'ENOENT') {
214
+ return false;
215
+ }
216
+ throw err;
217
+ }
218
+ });
219
+ return _fileExists.apply(this, arguments);
220
+ }
167
221
  const isNotNull = (n)=>Boolean(n);
168
222
 
169
223
  function _extends$1() {
@@ -207,9 +261,22 @@ function resolveTypescript(cwd) {
207
261
  }
208
262
  return ts;
209
263
  }
264
+ function getBuildEnv(envs) {
265
+ if (!envs.includes('NODE_ENV')) {
266
+ envs.push('NODE_ENV');
267
+ }
268
+ const envVars = envs.reduce((acc, key)=>{
269
+ const value = process.env[key];
270
+ if (typeof value !== 'undefined') {
271
+ acc['process.env.' + key] = JSON.stringify(value);
272
+ }
273
+ return acc;
274
+ }, {});
275
+ return envVars;
276
+ }
210
277
  function buildInputConfig(entry, pkg, options, { tsConfigPath , tsCompilerOptions , dtsOnly }) {
211
278
  var _options_external;
212
- const externals = [
279
+ const externals = options.noExternal ? [] : [
213
280
  pkg.peerDependencies,
214
281
  pkg.dependencies,
215
282
  pkg.peerDependenciesMeta
@@ -237,6 +304,10 @@ function buildInputConfig(entry, pkg, options, { tsConfigPath , tsCompilerOption
237
304
  })
238
305
  })
239
306
  ] : [
307
+ replace({
308
+ values: getBuildEnv(options.env || []),
309
+ preventAssignment: true
310
+ }),
240
311
  pluginNodeResolve.nodeResolve({
241
312
  preferBuiltins: runtime === 'node',
242
313
  extensions: [
@@ -337,11 +408,11 @@ function buildOutputConfigs(options, pkg, { tsCompilerOptions , dtsOnly }) {
337
408
  sourcemap: options.sourcemap
338
409
  });
339
410
  }
340
- function buildConfig(entry, pkg, cliArgs, dtsOnly) {
411
+ function buildConfig(entry, pkg, bundleConfig, dtsOnly) {
341
412
  var _options_exportCondition;
342
- const { file } = cliArgs;
413
+ const { file } = bundleConfig;
343
414
  const useTypescript = isTypescript(entry);
344
- const options = _extends$1({}, cliArgs, {
415
+ const options = _extends$1({}, bundleConfig, {
345
416
  useTypescript
346
417
  });
347
418
  let tsCompilerOptions = {};
@@ -349,7 +420,7 @@ function buildConfig(entry, pkg, cliArgs, dtsOnly) {
349
420
  if (useTypescript) {
350
421
  const ts = resolveTypescript(config.rootDir);
351
422
  tsConfigPath = path.resolve(config.rootDir, 'tsconfig.json');
352
- if (fs.existsSync(tsConfigPath)) {
423
+ if (fs$1.existsSync(tsConfigPath)) {
353
424
  const basePath = tsConfigPath ? path.dirname(tsConfigPath) : config.rootDir;
354
425
  const tsconfigJSON = ts.readConfigFile(tsConfigPath, ts.sys.readFile).config;
355
426
  tsCompilerOptions = ts.parseJsonConfigFileContent(tsconfigJSON, ts.sys, basePath).options;
@@ -369,7 +440,7 @@ function buildConfig(entry, pkg, cliArgs, dtsOnly) {
369
440
  // Generate dts job - single config
370
441
  if (dtsOnly) {
371
442
  outputConfigs = [
372
- buildOutputConfigs(_extends$1({}, cliArgs, {
443
+ buildOutputConfigs(_extends$1({}, bundleConfig, {
373
444
  format: 'es',
374
445
  useTypescript
375
446
  }), pkg, typescriptOptions)
@@ -377,7 +448,7 @@ function buildConfig(entry, pkg, cliArgs, dtsOnly) {
377
448
  } else {
378
449
  // multi outputs with specified format
379
450
  outputConfigs = outputExports.map((exportDist)=>{
380
- return buildOutputConfigs(_extends$1({}, cliArgs, {
451
+ return buildOutputConfigs(_extends$1({}, bundleConfig, {
381
452
  file: exportDist.file,
382
453
  format: exportDist.format,
383
454
  useTypescript
@@ -388,9 +459,9 @@ function buildConfig(entry, pkg, cliArgs, dtsOnly) {
388
459
  var _outputExports_;
389
460
  const fallbackFormat = (_outputExports_ = outputExports[0]) == null ? void 0 : _outputExports_.format;
390
461
  outputConfigs = [
391
- buildOutputConfigs(_extends$1({}, cliArgs, {
462
+ buildOutputConfigs(_extends$1({}, bundleConfig, {
392
463
  file,
393
- format: cliArgs.format || fallbackFormat,
464
+ format: bundleConfig.format || fallbackFormat,
394
465
  useTypescript
395
466
  }), pkg, typescriptOptions)
396
467
  ];
@@ -418,7 +489,7 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
418
489
  Promise.resolve(value).then(_next, _throw);
419
490
  }
420
491
  }
421
- function _asyncToGenerator(fn) {
492
+ function _async_to_generator(fn) {
422
493
  return function() {
423
494
  var self = this, args = arguments;
424
495
  return new Promise(function(resolve, reject) {
@@ -447,7 +518,7 @@ function _extends() {
447
518
  };
448
519
  return _extends.apply(this, arguments);
449
520
  }
450
- function _objectWithoutPropertiesLoose(source, excluded) {
521
+ function _object_without_properties_loose(source, excluded) {
451
522
  if (source == null) return {};
452
523
  var target = {};
453
524
  var sourceKeys = Object.keys(source);
@@ -459,6 +530,8 @@ function _objectWithoutPropertiesLoose(source, excluded) {
459
530
  }
460
531
  return target;
461
532
  }
533
+ const SRC = 'src' // resolve from src/ directory
534
+ ;
462
535
  function logBuild(exportPath, dtsOnly, duration) {
463
536
  logger.log(` ✓ ${dtsOnly ? 'Typed' : 'Built'} ${exportPath} ${formatDuration(duration)}`);
464
537
  }
@@ -467,34 +540,44 @@ function assignDefault(options, name, defaultValue) {
467
540
  options[name] = defaultValue;
468
541
  }
469
542
  }
470
- // Map '.' -> './index.[ext]'
471
- // Map './lite' -> './lite.[ext]'
543
+ function resolveSourceFile(cwd, filename) {
544
+ return path.resolve(cwd, SRC, filename);
545
+ }
472
546
  function getSourcePathFromExportPath(cwd, exportPath) {
473
- const exts = [
474
- 'js',
475
- 'cjs',
476
- 'mjs',
477
- 'jsx',
478
- 'ts',
479
- 'tsx'
480
- ];
481
- for (const ext of exts){
482
- // ignore package.json
483
- if (exportPath.endsWith('package.json')) return;
484
- if (exportPath === '.') exportPath = './index';
485
- const filename = path.resolve(cwd, `${exportPath}.${ext}`);
486
- if (fs.existsSync(filename)) {
487
- return filename;
547
+ return _getSourcePathFromExportPath.apply(this, arguments);
548
+ }
549
+ function _getSourcePathFromExportPath() {
550
+ _getSourcePathFromExportPath = // Map '.' -> './index.[ext]'
551
+ // Map './lite' -> './lite.[ext]'
552
+ // Return undefined if no match or if it's package.json exports
553
+ _async_to_generator(function*(cwd, exportPath) {
554
+ const exts = [
555
+ 'js',
556
+ 'cjs',
557
+ 'mjs',
558
+ 'jsx',
559
+ 'ts',
560
+ 'tsx'
561
+ ];
562
+ for (const ext of exts){
563
+ // ignore package.json
564
+ if (exportPath.endsWith('package.json')) return;
565
+ if (exportPath === '.') exportPath = './index';
566
+ const filename = resolveSourceFile(cwd, `${exportPath}.${ext}`);
567
+ if (yield fileExists(filename)) {
568
+ return filename;
569
+ }
488
570
  }
489
- }
490
- return;
571
+ return;
572
+ });
573
+ return _getSourcePathFromExportPath.apply(this, arguments);
491
574
  }
492
575
  function bundle(entryPath) {
493
576
  return _bundle.apply(this, arguments);
494
577
  }
495
578
  function _bundle() {
496
- _bundle = _asyncToGenerator(function*(entryPath, _param = {}) {
497
- var { cwd } = _param, options = _objectWithoutPropertiesLoose(_param, [
579
+ _bundle = _async_to_generator(function*(entryPath, _param = {}) {
580
+ var { cwd } = _param, options = _object_without_properties_loose(_param, [
498
581
  "cwd"
499
582
  ]);
500
583
  config.rootDir = path.resolve(process.cwd(), cwd || '');
@@ -504,28 +587,36 @@ function _bundle() {
504
587
  if (options.dts === undefined && isTypescript(entryPath)) {
505
588
  options.dts = true;
506
589
  }
507
- const pkg = getPackageMeta(config.rootDir);
590
+ const pkg = yield getPackageMeta(config.rootDir);
508
591
  const packageExports = pkg.exports || {};
509
592
  const isSingleEntry = typeof packageExports === 'string';
510
593
  const hasMultiEntries = packageExports && !isSingleEntry && Object.keys(packageExports).length > 0;
511
594
  if (isSingleEntry) {
512
- entryPath = getSourcePathFromExportPath(config.rootDir, '.');
595
+ // Use specified string file path if possible, then fallback to the default behavior entry picking logic
596
+ // e.g. "exports": "./dist/index.js" -> use "./index.<ext>" as entry
597
+ entryPath = entryPath || (yield getSourcePathFromExportPath(config.rootDir, '.')) || '';
513
598
  }
514
599
  function buildEntryConfig(packageExports, dtsOnly) {
515
- const configs = Object.keys(packageExports).map((entryExport)=>{
516
- const source = getSourcePathFromExportPath(config.rootDir, entryExport);
517
- if (!source) return undefined;
518
- if (dtsOnly && !isTypescript(source)) return;
519
- options.exportCondition = {
520
- source,
521
- name: entryExport,
522
- export: packageExports[entryExport]
523
- };
524
- const entry = path.resolve(cwd, source);
525
- const rollupConfig = buildConfig(entry, pkg, options, dtsOnly);
526
- return rollupConfig;
527
- }).filter((v)=>!!v);
528
- return configs;
600
+ return _buildEntryConfig.apply(this, arguments);
601
+ }
602
+ function _buildEntryConfig() {
603
+ _buildEntryConfig = _async_to_generator(function*(packageExports, dtsOnly) {
604
+ const configs = Object.keys(packageExports).map(/*#__PURE__*/ _async_to_generator(function*(entryExport) {
605
+ const source = yield getSourcePathFromExportPath(config.rootDir, entryExport);
606
+ if (!source) return undefined;
607
+ if (dtsOnly && !isTypescript(source)) return;
608
+ options.exportCondition = {
609
+ source,
610
+ name: entryExport,
611
+ export: packageExports[entryExport]
612
+ };
613
+ const entry = resolveSourceFile(cwd, source);
614
+ const rollupConfig = buildConfig(entry, pkg, options, dtsOnly);
615
+ return rollupConfig;
616
+ }));
617
+ return (yield Promise.all(configs)).filter((n)=>Boolean(n));
618
+ });
619
+ return _buildEntryConfig.apply(this, arguments);
529
620
  }
530
621
  const bundleOrWatch = (rollupConfig)=>{
531
622
  const { input , exportName } = rollupConfig;
@@ -540,8 +631,8 @@ function _bundle() {
540
631
  }
541
632
  return runBundle(rollupConfig, buildMetadata);
542
633
  };
543
- if (!fs.existsSync(entryPath)) {
544
- const hasSpecifiedEntryFile = entryPath === '' ? false : fs.statSync(entryPath).isFile();
634
+ if (!(yield fileExists(entryPath))) {
635
+ const hasSpecifiedEntryFile = entryPath === '' ? false : (yield fs.stat(entryPath)).isFile();
545
636
  if (!hasSpecifiedEntryFile && !hasMultiEntries) {
546
637
  const err = new Error(`Entry file \`${entryPath}\` is not existed`);
547
638
  err.name = 'NOT_EXISTED';
@@ -554,8 +645,9 @@ function _bundle() {
554
645
  options.dts = hasTypings;
555
646
  }
556
647
  if (hasMultiEntries) {
557
- const assetsJobs = buildEntryConfig(packageExports, false).map((rollupConfig)=>bundleOrWatch(rollupConfig));
558
- const typesJobs = options.dts ? buildEntryConfig(packageExports, true).map((rollupConfig)=>bundleOrWatch(rollupConfig)) : [];
648
+ const buildConfigs = yield buildEntryConfig(packageExports, false);
649
+ const assetsJobs = buildConfigs.map((rollupConfig)=>bundleOrWatch(rollupConfig));
650
+ const typesJobs = options.dts ? (yield buildEntryConfig(packageExports, true)).map((rollupConfig)=>bundleOrWatch(rollupConfig)) : [];
559
651
  return yield Promise.all(assetsJobs.concat(typesJobs));
560
652
  }
561
653
  }
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "bunchee",
3
- "version": "3.0.0-beta.10",
3
+ "version": "3.0.0-beta.12",
4
4
  "description": "zero config bundler for js/ts/jsx libraries",
5
5
  "bin": {
6
6
  "bunchee": "./dist/cli.js"
7
7
  },
8
- "main": "./dist/lib.js",
9
- "types": "./dist/lib.d.ts",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
10
  "scripts": {
11
11
  "test": "jest --env node",
12
12
  "test:update": "TEST_UPDATE_SNAPSHOT=1 yarn test",
13
13
  "clean": "rm -rf ./dist",
14
14
  "typecheck": "tsc --noEmit",
15
15
  "prepublishOnly": "yarn clean && yarn build && chmod +x ./dist/cli.js && yarn test",
16
- "build:cli": "tsx ./cli.ts ./cli.ts --runtime node -f cjs -o ./dist/cli.js",
17
- "build:main": "tsx ./cli.ts ./lib.ts --runtime node -f cjs",
16
+ "build:cli": "tsx ./src/cli.ts ./src/cli.ts --runtime node -f cjs -o ./dist/cli.js",
17
+ "build:main": "tsx ./src/cli.ts ./src/index.ts --runtime node -f cjs",
18
18
  "build": "yarn build:main && yarn build:cli"
19
19
  },
20
20
  "type": "commonjs",
@@ -31,6 +31,9 @@
31
31
  "dist",
32
32
  "*.md"
33
33
  ],
34
+ "engines": {
35
+ "node": ">= 16"
36
+ },
34
37
  "author": "huozhi (github.com/huozhi)",
35
38
  "repository": {
36
39
  "type": "git",
@@ -40,14 +43,16 @@
40
43
  "dependencies": {
41
44
  "@rollup/plugin-commonjs": "24.0.1",
42
45
  "@rollup/plugin-json": "6.0.0",
43
- "@rollup/plugin-node-resolve": "15.0.1",
44
- "@swc/core": "1.3.35",
46
+ "@rollup/plugin-node-resolve": "15.0.2",
47
+ "@rollup/plugin-replace": "5.0.2",
48
+ "@swc/core": "1.3.46",
45
49
  "arg": "5.0.2",
46
- "rollup": "3.15.0",
47
- "rollup-plugin-dts": "5.1.1",
50
+ "publint": "0.1.11",
51
+ "rollup": "3.20.2",
52
+ "rollup-plugin-dts": "5.3.0",
48
53
  "rollup-plugin-preserve-shebang": "1.0.1",
49
- "rollup-plugin-swc3": "0.8.0",
50
- "tslib": "2.4.0"
54
+ "rollup-plugin-swc3": "0.8.1",
55
+ "tslib": "2.5.0"
51
56
  },
52
57
  "peerDependencies": {
53
58
  "typescript": ">= 3.7.0"
@@ -58,11 +63,12 @@
58
63
  }
59
64
  },
60
65
  "devDependencies": {
66
+ "@huozhi/testing-package": "1.0.0",
61
67
  "@swc/jest": "0.2.22",
62
68
  "@types/jest": "29.0.0",
63
69
  "jest": "29.0.1",
64
70
  "react": "18.2.0",
65
- "tsx": "3.12.3",
71
+ "tsx": "3.12.6",
66
72
  "typescript": "4.9.5"
67
73
  },
68
74
  "jest": {
@@ -70,7 +76,7 @@
70
76
  "node_modules"
71
77
  ],
72
78
  "moduleNameMapper": {
73
- "bunchee": "<rootDir>/lib.ts"
79
+ "bunchee": "<rootDir>/src/index.ts"
74
80
  },
75
81
  "transform": {
76
82
  "^.+\\.(t|j)sx?$": [