Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[wip] multi-entry #929

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
152 changes: 152 additions & 0 deletions _old_getMain.js.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
function replaceName(filename, name) {
return resolve(
dirname(filename),
name + basename(filename).replace(/^[^.]+/, ''),
);
}

/**
* @param {any} exports - package.json "exports" field value
* @param {string} exportPath - the export to look up (eg: '.', './a', './b/c')
* @param {string[]} conditions - conditional export keys to use (note: unlike in resolution, order here *does* define precedence!)
* @param {RegExp|string} [defaultPattern] - only use (resolved) default export filenames that match this pattern
* @param {string} [condition] - (internal) the nearest condition key on the stack
*/
function walk(exports, exportPath, conditions, defaultPattern, condition) {
if (!exports) return;
if (typeof exports === 'string') {
if (
condition === 'default' &&
defaultPattern &&
!exports.match(defaultPattern)
) {
return;
}
return exports;
}
if (Array.isArray(exports)) {
for (const map of exports) {
const r = walk(map, exportPath, conditions, defaultPattern, condition);
if (r) return r;
}
return;
}
const map = exports[exportPath];
if (map) {
const r = walk(map, exportPath, conditions, defaultPattern, condition);
if (r) return r;
}
for (const condition of conditions) {
const map = exports[condition];
if (!map) continue;
const r = walk(map, exportPath, conditions, defaultPattern, condition);
if (r) return r;
}
// return walk(exports['.'] || exports.import || exports.module);
}

function getMain({ options, entry, format }) {
const { pkg } = options;
const pkgMain = options['pkg-main'];

if (!pkgMain) {
return options.output;
}

// package.json export name (see https://nodejs.org/api/packages.html#packages_subpath_exports)
let exportPath = '.';
let mainNoExtension = options.output;
if (options.multipleEntries) {
const commonDir = options.entries
.reduce((acc, entry) => {
entry = dirname(entry).split(sep);
if (!acc) return entry;
if (entry.length < acc.length) acc.length = entry.length;
let last = entry.length - 1;
while (entry[last] !== acc[last]) {
last--;
acc.pop();
}
return acc;
}, undefined)
.join(sep);
console.log('>>>>>', { first: options.entries[0], commonDir });

const isMainEntry = entry.match(
/([\\/])index(\.(umd|cjs|es|m))?\.(mjs|cjs|[tj]sx?)$/,
);
let name = isMainEntry ? mainNoExtension : entry;
mainNoExtension = resolve(dirname(mainNoExtension), basename(name));
if (!isMainEntry) {
exportPath =
'./' +
posix.relative(commonDir, entry.replace(/\.([mc]js|[tj]sx?)$/g, ''));
}
}
mainNoExtension = mainNoExtension.replace(
/(\.(umd|cjs|es|m))?\.(mjs|cjs|[tj]sx?)$/,
'',
);

const mainsByFormat = {};

const MJS = pkg.type === 'module' ? /\.m?js$/i : /\.mjs$/i;
const CJS = pkg.type === 'module' ? /\.cjs$/i : /\.js$/i;
const UMD = /[.-]umd\.c?js$/i;
const CONDITIONS_MJS = ['import', 'module', 'default'];
const CONDITIONS_MODERN = ['modern', 'esmodules', ...CONDITIONS_MJS];
const CONDITIONS_CJS = ['require', 'default'];
const CONDITIONS_UMD = ['umd', 'default'];

mainsByFormat.modern =
walk(pkg.exports, exportPath, CONDITIONS_MODERN, MJS) ||
(pkg.syntax && pkg.syntax.esmodules) ||
pkg.esmodule ||
replaceName('x.modern.js', mainNoExtension);

mainsByFormat.es = walk(pkg.exports, exportPath, CONDITIONS_MJS, MJS);
if (!mainsByFormat.es || mainsByFormat.es === mainsByFormat.modern) {
mainsByFormat.es =
pkg.module && !pkg.module.match(/src\//)
? pkg.module
: pkg['jsnext:main'] || replaceName('x.esm.js', mainNoExtension);
}

mainsByFormat.umd =
walk(pkg.exports, exportPath, CONDITIONS_UMD, UMD) ||
pkg['umd:main'] ||
pkg.unpkg ||
replaceName('x.umd.js', mainNoExtension);

mainsByFormat.cjs = walk(pkg.exports, exportPath, CONDITIONS_CJS, CJS);
if (!mainsByFormat.cjs || mainsByFormat.cjs === mainsByFormat.umd) {
mainsByFormat.cjs =
pkg['cjs:main'] ||
replaceName(pkg.type === 'module' ? 'x.cjs' : 'x.js', mainNoExtension);
}

if (pkg.type === 'module') {
let errors = [];
let filenames = [];
if (mainsByFormat.cjs.endsWith('.js')) {
errors.push('CommonJS');
filenames.push(` "cjs:main": "${mainsByFormat.cjs}",`);
}
if (mainsByFormat.umd.endsWith('.js')) {
errors.push('CommonJS');
const field = pkg['umd:main'] ? 'umd:main' : 'unpkg';
filenames.push(` "${field}": "${mainsByFormat.umd}",`);
}
if (errors.length) {
const warning =
`Warning: A package.json with {"type":"module"} should use .cjs file extensions for` +
` ${errors.join(' and ')} filename${errors.length == 1 ? '' : 's'}:` +
`\n${filenames.join('\n')}`;
stderr(yellow(warning));
}
}

console.log('>> MAIN: ', format, entry, exportPath, mainsByFormat[format]);

return mainsByFormat[format] || mainsByFormat.cjs;
}
12 changes: 11 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@
"@babel/plugin-proposal-throw-expressions": "^7.12.1",
"@changesets/changelog-github": "^0.2.7",
"@changesets/cli": "^2.12.0",
"@types/jest": "^26.0.23",
"babel-jest": "^26.6.3",
"cross-env": "^7.0.3",
"directory-tree": "^2.2.5",
Expand Down
80 changes: 14 additions & 66 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs';
import { resolve, relative, dirname, basename, extname } from 'path';
import camelCase from 'camelcase';
import escapeStringRegexp from 'escape-string-regexp';
import { blue } from 'kleur';
import { blue, yellow } from 'kleur';
import { map, series } from 'asyncro';
import glob from 'tiny-glob/sync';
import autoprefixer from 'autoprefixer';
Expand All @@ -19,7 +19,7 @@ import postcss from 'rollup-plugin-postcss';
import typescript from 'rollup-plugin-typescript2';
import json from '@rollup/plugin-json';
import logError from './log-error';
import { isDir, isFile, stdout, isTruthy, removeScope } from './utils';
import { isDir, isFile, stdout, isTruthy, removeScope, stderr } from './utils';
import { getSizeInfo } from './lib/compressed-size';
import { normalizeMinifyOptions } from './lib/terser';
import {
Expand All @@ -29,6 +29,7 @@ import {
} from './lib/option-normalization';
import { getConfigFromPkgJson, getName } from './lib/package-info';
import { shouldCssModules, cssModulesConfig } from './lib/css-modules';
import { computeEntries } from './lib/compute-entries';

// Extensions to use when resolving modules
const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.es6', '.es', '.mjs'];
Expand Down Expand Up @@ -61,8 +62,10 @@ export default async function microbundle(inputOptions) {
options.pkg.name = pkgName;

if (options.sourcemap === 'inline') {
console.log(
'Warning: inline sourcemaps should only be used for debugging purposes.',
stderr(
yellow(
'Warning: inline sourcemaps should only be used for debugging purposes.',
),
);
} else if (options.sourcemap === 'false') {
options.sourcemap = false;
Expand Down Expand Up @@ -249,67 +252,6 @@ async function getEntries({ input, cwd }) {
return entries;
}

function replaceName(filename, name) {
return resolve(
dirname(filename),
name + basename(filename).replace(/^[^.]+/, ''),
);
}

function walk(exports) {
if (typeof exports === 'string') return exports;
return walk(exports['.'] || exports.import || exports.module);
}

function getMain({ options, entry, format }) {
const { pkg } = options;
const pkgMain = options['pkg-main'];

if (!pkgMain) {
return options.output;
}

let mainNoExtension = options.output;
if (options.multipleEntries) {
let name = entry.match(
/([\\/])index(\.(umd|cjs|es|m))?\.(mjs|cjs|[tj]sx?)$/,
)
? mainNoExtension
: entry;
mainNoExtension = resolve(dirname(mainNoExtension), basename(name));
}
mainNoExtension = mainNoExtension.replace(
/(\.(umd|cjs|es|m))?\.(mjs|cjs|[tj]sx?)$/,
'',
);

const mainsByFormat = {};

mainsByFormat.es = replaceName(
pkg.module && !pkg.module.match(/src\//)
? pkg.module
: pkg['jsnext:main'] || 'x.esm.js',
mainNoExtension,
);
mainsByFormat.modern = replaceName(
(pkg.exports && walk(pkg.exports)) ||
(pkg.syntax && pkg.syntax.esmodules) ||
pkg.esmodule ||
'x.modern.js',
mainNoExtension,
);
mainsByFormat.cjs = replaceName(
pkg['cjs:main'] || (pkg.type && pkg.type === 'module' ? 'x.cjs' : 'x.js'),
mainNoExtension,
);
mainsByFormat.umd = replaceName(
pkg['umd:main'] || pkg.unpkg || 'x.umd.js',
mainNoExtension,
);

return mainsByFormat[format] || mainsByFormat.cjs;
}

// shebang cache map because the transform only gets run once
const shebang = {};

Expand Down Expand Up @@ -417,7 +359,13 @@ function createConfig(options, entry, format, writeMeta) {
let cache;
if (modern) cache = false;

const absMain = resolve(options.cwd, getMain({ options, entry, format }));
const entries = computeEntries({
...options,
entry,
format,
});
const absMain = resolve('.', options.cwd, entries[format] || entries.cjs);
console.log(entries[format], absMain);
const outputDir = dirname(absMain);
const outputEntryFileName = basename(absMain);

Expand Down
Loading