Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ bili --format esm
bili --format cjs --format esm
```

To also generate modern bundles for browsers with native ES module support:

```bash
bili --format esm --modern
```

And you want minified bundles?

```bash
Expand Down
48 changes: 27 additions & 21 deletions src/babel/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,51 +8,57 @@ export default (
asyncToPromises = process.env.BILI_ASYNC_TO_PROMISES,
jsx = process.env.BILI_JSX,
objectAssign = process.env.BILI_OBJECT_ASSIGN,
minimal = process.env.BILI_MINIMAL
minimal = process.env.BILI_MINIMAL,
modern = process.env.BILI_MODERN,
} = {}
) => {
const presets = [
!minimal && [
require('@babel/preset-env').default,
{
modules: ENV === 'test' ? 'auto' : false,
exclude: [
'transform-regenerator',
'transform-async-to-generator',
'proposal-object-rest-spread'
]
}
const presetEnvOptions: any = {
modules: ENV === 'test' ? 'auto' : false,
exclude: [
'transform-regenerator',
'transform-async-to-generator',
'proposal-object-rest-spread',
],
require('@babel/preset-typescript')
}

if (modern) {
presetEnvOptions.targets = {
esmodules: true,
}
}

const presets = [
!minimal && [require('@babel/preset-env').default, presetEnvOptions],
require('@babel/preset-typescript'),
].filter(Boolean)

const plugins = [
[
require('@babel/plugin-transform-react-jsx'),
{
pragma: jsx === 'react' ? 'React.createElement' : jsx
}
pragma: jsx === 'react' ? 'React.createElement' : jsx,
},
],
[
require('@babel/plugin-proposal-object-rest-spread'),
{
useBuiltIns: true,
loose: true
}
loose: true,
},
],
[require('@babel/plugin-proposal-optional-chaining')],
[require('@babel/plugin-proposal-nullish-coalescing-operator')],
[
alterObjectAssign,
{
objectAssign
}
objectAssign,
},
],
asyncToPromises && require('babel-plugin-transform-async-to-promises')
asyncToPromises && require('babel-plugin-transform-async-to-promises'),
].filter(Boolean)

return {
presets,
plugins
plugins,
}
}
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ cli
.option('-t, --target <target>', 'Output target', { default: 'node' })
.option('-c, --config <file>', 'Use a custom config file')
.option('--minimal', 'Generate minimal output whenever possible')
.option(
'--modern',
'Generate an additional modern bundle for browsers with native ES module support'
)
.option('--no-babelrc', 'Disable .babelrc file')
.option('--banner', 'Add banner with pkg info to the bundle')
.option(
Expand Down Expand Up @@ -72,6 +76,7 @@ cli
sourceMap: options.map,
sourceMapExcludeSources: options.mapExcludeSources,
target: options.target,
modern: options.modern,
},
bundleNodeModules: options.bundleNodeModules,
env: options.env,
Expand Down
86 changes: 56 additions & 30 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ interface RollupConfigInput {
}
title: string
format: Format
modern: boolean
context: RunContext
assets: Assets
config: NormalizedConfig
Expand Down Expand Up @@ -153,11 +154,21 @@ export class Bundler {
async createRollupConfig({
source,
format,
modern,
title,
context,
assets,
config,
}: RollupConfigInput): Promise<RollupConfig> {
if (modern) {
config = merge({}, config, {
babel: {
asyncToPromises: false,
modern: true,
},
})
}

// Always minify if config.minify is truthy
// Otherwise infer by format
const minify =
Expand Down Expand Up @@ -455,16 +466,22 @@ export class Bundler {
const getFileName = config.output.fileName || defaultFileName
const fileNameTemplate =
typeof getFileName === 'function'
? getFileName({ format: rollupFormat, minify }, defaultFileName)
? getFileName({ format: rollupFormat, minify, modern }, defaultFileName)
: getFileName
const hasModernPlaceholder = fileNameTemplate.includes('[modern]')
let fileName = fileNameTemplate
.replace(/\[modern\]/, modern ? '.modern' : '')
.replace(/\[min\]/, minPlaceholder)
// The `[ext]` placeholder no longer makes sense
// Since we only output to `.js` now
// Probably remove it in the future
.replace(/\[ext\]/, '.js')

if (rollupFormat === 'esm') {

if (modern && !hasModernPlaceholder) {
fileName = fileName.replace(/(\.[^./]+)$/, '.modern$1')
}

if (rollupFormat === 'esm') {
fileName = fileName.replace(/\[format\]/, 'esm')
}

Expand Down Expand Up @@ -582,34 +599,43 @@ export class Bundler {

for (const source of sources) {
for (const format of formats) {
let title = `Bundle ${source.files.join(', ')} in ${format} format`
if (target) {
title += ` for target ${target}`
for (const modern of this.config.output.modern
? [false, true]
: [false]) {
let title = `Bundle ${source.files.join(', ')} in ${format} format`
if (target) {
title += ` for target ${target}`
}
if (modern) {
title += ' as modern bundle'
}
tasks.push({
title,
modern,
getConfig: async (context, task) => {
const assets: Assets = new Map()
this.bundles.add(assets)
const config = this.config.extendConfig
? this.config.extendConfig(merge({}, this.config), {
input: source.input,
format,
})
: this.config
const rollupConfig = await this.createRollupConfig({
source,
format,
modern: task.modern,
title: task.title,
context,
assets,
config,
})
return this.config.extendRollupConfig
? this.config.extendRollupConfig(rollupConfig)
: rollupConfig
},
})
}
tasks.push({
title,
getConfig: async (context, task) => {
const assets: Assets = new Map()
this.bundles.add(assets)
const config = this.config.extendConfig
? this.config.extendConfig(merge({}, this.config), {
input: source.input,
format,
})
: this.config
const rollupConfig = await this.createRollupConfig({
source,
format,
title: task.title,
context,
assets,
config,
})
return this.config.extendRollupConfig
? this.config.extendRollupConfig(rollupConfig)
: rollupConfig
},
})
}
}

Expand Down
16 changes: 12 additions & 4 deletions src/plugins/babel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ import { BabelPresetOptions } from '../types'
export const a = 1

export default createBabelInputPluginFactory((babelCore) => {
const presetItem = babelCore.createConfigItem(preset, {
type: 'preset',
})

return {
// Passed the plugin options.
options({
Expand Down Expand Up @@ -42,6 +38,8 @@ export default createBabelInputPluginFactory((babelCore) => {
// And our options will still work
if (presetOptions.asyncToPromises) {
process.env.BILI_ASYNC_TO_PROMISES = 'enabled'
} else {
delete process.env.BILI_ASYNC_TO_PROMISES
}

if (presetOptions.jsx) {
Expand All @@ -56,6 +54,16 @@ export default createBabelInputPluginFactory((babelCore) => {
process.env.BILI_MINIMAL = 'enabled'
}

if (presetOptions.modern) {
process.env.BILI_MODERN = 'enabled'
} else {
delete process.env.BILI_MODERN
}

const presetItem = babelCore.createConfigItem([preset, presetOptions], {
type: 'preset',
})

return {
...cfg.options,
presets: [
Expand Down
14 changes: 13 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
ModuleFormat as RollupFormat,
InputOptions,
OutputOptions,
Plugin as RollupPlugin
Plugin as RollupPlugin,
} from 'rollup'

import { Banner } from './utils/get-banner'
Expand Down Expand Up @@ -46,6 +46,7 @@ export interface RunContext {

export interface Task {
title: string
modern: boolean
getConfig(context: RunContext, task: Task): Promise<RollupConfig>
}

Expand All @@ -67,6 +68,7 @@ export type ExtendRollupConfig = (config: RollupConfig) => RollupConfig
export interface FileNameContext {
format: RollupFormat
minify: boolean
modern: boolean
}

export type GetFileName = (
Expand Down Expand Up @@ -103,6 +105,10 @@ export interface BabelPresetOptions {
* In addtional we use rollup-plugin-buble after rollup-plugin-babel
*/
minimal?: boolean
/**
* Target browsers with native ES module support.
*/
modern?: boolean
}

export type OutputTarget = 'node' | 'browser'
Expand Down Expand Up @@ -167,6 +173,12 @@ export interface ConfigOutput {
* @cli `--target <target>`
*/
target?: OutputTarget
/**
* Generate an additional modern bundle for browsers with native ES module support.
* Modern bundles use Babel's `esmodules` target and append `.modern` to output file names.
* @cli `--modern`
*/
modern?: boolean
}

export interface Config {
Expand Down
28 changes: 28 additions & 0 deletions test/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,34 @@ module.exports = index;
"
`;

exports[`modern: modern dist/index.esm.js 1`] = `
"function _await(value, then, direct) {
if (direct) {
return then ? then(value) : value;
}

if (!value || !value.then) {
value = Promise.resolve(value);
}

return then ? value.then(then) : value;
}

var index = (function (value) {
return _await(value);
});

export default index;
"
`;

exports[`modern: modern dist/index.esm.modern.js 1`] = `
"var index = (async value => await value);

export default index;
"
`;

exports[`target:browser: target:browser dist/index.js 1`] = `
"'use strict';

Expand Down
1 change: 1 addition & 0 deletions test/fixtures/modern/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default async (value) => await value
Loading