cli: add exports support for package builds

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2023-01-14 14:16:34 +01:00
parent b4cd145b57
commit a9b88cda17
8 changed files with 203 additions and 98 deletions
@@ -37,6 +37,7 @@ export async function buildBackend(options: BuildBackendOptions) {
// We build the target package without generating type declarations.
await buildPackage({
targetDir: options.targetDir,
packageJson: pkg,
outputs: new Set([Output.cjs]),
});
+1
View File
@@ -130,6 +130,7 @@ export async function command(opts: OptionValues, cmd: Command): Promise<void> {
return {
targetDir: pkg.dir,
packageJson: pkg.packageJson,
outputs,
logPrefix: `${chalk.cyan(relativePath(paths.targetRoot, pkg.dir))}: `,
minify: buildOptions.minify,
@@ -24,6 +24,11 @@ describe('makeRollupConfigs', () => {
const [config] = await makeRollupConfigs({
outputs: new Set([Output.cjs]),
packageJson: {
name: 'test',
version: '0.0.0',
main: './src/index.ts',
},
});
const external = config.external as Exclude<
ExternalOption,
+116 -98
View File
@@ -31,6 +31,10 @@ import { forwardFileImports } from './plugins';
import { BuildOptions, Output } from './types';
import { paths } from '../paths';
import { svgrTemplate } from '../svgrTemplate';
import { ExtendedPackageJSON } from '../monorepo';
import { readEntryPoints } from '../monorepo/entryPoints';
const SCRIPT_EXTS = ['.js', '.jsx', '.ts', '.tsx'];
function isFileImport(source: string) {
if (source.startsWith('.')) {
@@ -50,6 +54,13 @@ export async function makeRollupConfigs(
): Promise<RollupOptions[]> {
const configs = new Array<RollupOptions>();
const targetDir = options.targetDir ?? paths.targetDir;
let targetPkg = options.packageJson;
if (!targetPkg) {
const packagePath = resolvePath(targetDir, 'package.json');
targetPkg = (await fs.readJson(packagePath)) as ExtendedPackageJSON;
}
const onwarn = ({ code, message }: RollupWarning) => {
if (code === 'EMPTY_BUNDLE') {
return; // We don't care about this one
@@ -62,111 +73,118 @@ export async function makeRollupConfigs(
};
const distDir = resolvePath(targetDir, 'dist');
const entryPoints = readEntryPoints(targetPkg);
if (options.outputs.has(Output.cjs) || options.outputs.has(Output.esm)) {
const output = new Array<OutputOptions>();
const mainFields = ['module', 'main'];
if (options.outputs.has(Output.cjs)) {
output.push({
dir: distDir,
entryFileNames: 'index.cjs.js',
chunkFileNames: 'cjs/[name]-[hash].cjs.js',
format: 'commonjs',
sourcemap: true,
});
}
if (options.outputs.has(Output.esm)) {
output.push({
dir: distDir,
entryFileNames: 'index.esm.js',
chunkFileNames: 'esm/[name]-[hash].esm.js',
format: 'module',
sourcemap: true,
});
// Assume we're building for the browser if ESM output is included
mainFields.unshift('browser');
for (const { path, name, ext } of entryPoints) {
if (!SCRIPT_EXTS.includes(ext)) {
continue;
}
configs.push({
input: resolvePath(targetDir, 'src/index.ts'),
output,
onwarn,
preserveEntrySignatures: 'strict',
// All module imports are always marked as external
external: (source, importer, isResolved) =>
Boolean(importer && !isResolved && !isFileImport(source)),
plugins: [
resolve({ mainFields }),
commonjs({
include: /node_modules/,
exclude: [/\/[^/]+\.(?:stories|test)\.[^/]+$/],
}),
postcss(),
forwardFileImports({
exclude: /\.icon\.svg$/,
include: [
/\.svg$/,
/\.png$/,
/\.gif$/,
/\.jpg$/,
/\.jpeg$/,
/\.eot$/,
/\.woff$/,
/\.woff2$/,
/\.ttf$/,
],
}),
json(),
yaml(),
svgr({
include: /\.icon\.svg$/,
template: svgrTemplate,
}),
esbuild({
target: 'es2019',
minify: options.minify,
}),
],
});
}
if (options.outputs.has(Output.cjs) || options.outputs.has(Output.esm)) {
const output = new Array<OutputOptions>();
const mainFields = ['module', 'main'];
if (options.outputs.has(Output.types) && !options.useApiExtractor) {
const typesInput = paths.resolveTargetRoot(
'dist-types',
relativePath(paths.targetRoot, targetDir),
'src/index.d.ts',
);
if (options.outputs.has(Output.cjs)) {
output.push({
dir: distDir,
entryFileNames: `${name}.cjs.js`,
chunkFileNames: `cjs/${name}/[name]-[hash].cjs.js`,
format: 'commonjs',
sourcemap: true,
});
}
if (options.outputs.has(Output.esm)) {
output.push({
dir: distDir,
entryFileNames: `${name}.esm.js`,
chunkFileNames: `esm/${name}/[name]-[hash].esm.js`,
format: 'module',
sourcemap: true,
});
// Assume we're building for the browser if ESM output is included
mainFields.unshift('browser');
}
const declarationsExist = await fs.pathExists(typesInput);
if (!declarationsExist) {
const path = relativePath(targetDir, typesInput);
throw new Error(
`No declaration files found at ${path}, be sure to run ${chalk.bgRed.white(
'yarn tsc',
)} to generate .d.ts files before packaging`,
configs.push({
input: resolvePath(targetDir, path),
output,
onwarn,
preserveEntrySignatures: 'strict',
// All module imports are always marked as external
external: (source, importer, isResolved) =>
Boolean(importer && !isResolved && !isFileImport(source)),
plugins: [
resolve({ mainFields }),
commonjs({
include: /node_modules/,
exclude: [/\/[^/]+\.(?:stories|test)\.[^/]+$/],
}),
postcss(),
forwardFileImports({
exclude: /\.icon\.svg$/,
include: [
/\.svg$/,
/\.png$/,
/\.gif$/,
/\.jpg$/,
/\.jpeg$/,
/\.eot$/,
/\.woff$/,
/\.woff2$/,
/\.ttf$/,
],
}),
json(),
yaml(),
svgr({
include: /\.icon\.svg$/,
template: svgrTemplate,
}),
esbuild({
target: 'es2019',
minify: options.minify,
}),
],
});
}
if (options.outputs.has(Output.types) && !options.useApiExtractor) {
const typesInput = paths.resolveTargetRoot(
'dist-types',
relativePath(paths.targetRoot, targetDir),
path.replace(/\.ts$/, '.d.ts'),
);
}
configs.push({
input: typesInput,
output: {
file: resolvePath(distDir, 'index.d.ts'),
format: 'es',
},
external: [
/\.css$/,
/\.scss$/,
/\.sass$/,
/\.svg$/,
/\.eot$/,
/\.woff$/,
/\.woff2$/,
/\.ttf$/,
],
onwarn,
plugins: [dts()],
});
const declarationsExist = await fs.pathExists(typesInput);
if (!declarationsExist) {
const declarationPath = relativePath(targetDir, typesInput);
throw new Error(
`No declaration files found at ${declarationPath}, be sure to run ${chalk.bgRed.white(
'yarn tsc',
)} to generate .d.ts files before packaging`,
);
}
configs.push({
input: typesInput,
output: {
file: resolvePath(distDir, `${name}.d.ts`),
format: 'es',
},
external: [
/\.css$/,
/\.scss$/,
/\.sass$/,
/\.svg$/,
/\.eot$/,
/\.woff$/,
/\.woff2$/,
/\.ttf$/,
],
onwarn,
plugins: [dts()],
});
}
}
return configs;
+3
View File
@@ -14,6 +14,8 @@
* limitations under the License.
*/
import { ExtendedPackageJSON } from '../monorepo';
export enum Output {
esm,
cjs,
@@ -23,6 +25,7 @@ export enum Output {
export type BuildOptions = {
logPrefix?: string;
targetDir?: string;
packageJson?: ExtendedPackageJSON;
outputs: Set<Output>;
minify?: boolean;
useApiExtractor?: boolean;
@@ -25,6 +25,9 @@ import { JsonValue } from '@backstage/types';
type PackageJSON = Package['packageJson'];
export interface ExtendedPackageJSON extends PackageJSON {
main?: string;
module?: string;
scripts?: {
[key: string]: string;
};
@@ -0,0 +1,73 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { extname } from 'path';
import { ExtendedPackageJSON } from './PackageGraph';
export interface EntryPoint {
mount: string;
path: string;
name: string;
ext: string;
}
function parseEntryPoint(mount: string, path: string): EntryPoint {
let name = mount;
if (name === '.') {
name = 'index';
} else if (name.startsWith('./')) {
name = name.slice(2);
}
if (name.includes('/')) {
throw new Error(`Mount point '${mount}' may not contain multiple slashes`);
}
return { mount, path, name, ext: extname(path) };
}
export function readEntryPoints(pkg: ExtendedPackageJSON): Array<EntryPoint> {
const exp = pkg.exports;
if (typeof exp === 'string') {
return [parseEntryPoint('.', exp)];
} else if (exp && typeof exp === 'object' && !Array.isArray(exp)) {
const entryPoints = new Array<{
mount: string;
path: string;
name: string;
ext: string;
}>();
for (const mount of Object.keys(exp)) {
const path = exp[mount];
if (typeof path !== 'string') {
throw new Error(
`Exports field value must be a string, got '${JSON.stringify(path)}'`,
);
}
entryPoints.push(parseEntryPoint(mount, path));
}
return entryPoints;
}
const main = pkg.main || pkg.module;
if (main) {
return [parseEntryPoint('.', main)];
}
return [];
}
@@ -178,6 +178,7 @@ export async function createDistWorkspace(
if (outputs.size > 0) {
standardBuilds.push({
targetDir: pkg.dir,
packageJson: pkg.packageJson,
outputs: outputs,
logPrefix: `${chalk.cyan(relativePath(paths.targetRoot, pkg.dir))}: `,
// No need to detect these for the backend builds, we assume no minification or types