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
9 changes: 9 additions & 0 deletions .changeset/cjs-require-entry-points.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"react-datocms": patch
---

`require("react-datocms")` and every `require` of a subpath (`react-datocms/seo`,
`react-datocms/image`, …) threw `ReferenceError: exports is not defined in ES
module scope` on Node. The CommonJS build in `dist/cjs` now carries its own
`package.json` with `"type": "commonjs"`, so Node loads it as CommonJS. `import`
and bundled apps are unaffected.
14 changes: 14 additions & 0 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,17 @@ jobs:
cache: "npm"
- run: npm ci
- run: npm test

package:
# Loads every entry point of the packed tarball with `require` and `import`,
# which `npm test` (source only) can't catch.
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "npm"
- run: npm ci
- run: npm run test:package
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,10 @@
"watch": "rimraf dist && tsc --project ./tsconfig.commonjs.json --watch",
"prepare": "npm run test && npm run build",
"test": "jest --coverage",
"test:package": "npm run build && node scripts/test-package.mjs",
"toc": "doctoc --github docs",
"tsc:types": "tsc",
"tsc:cjs": "tsc --project ./tsconfig.commonjs.json",
"tsc:cjs": "tsc --project ./tsconfig.commonjs.json && node scripts/copy-cjs-package-json.mjs",
"tsc:esm": "tsc --project ./tsconfig.esnext.json",
"changeset": "changeset",
"release": "release-toolchain",
Expand Down
3 changes: 3 additions & 0 deletions scripts/cjs-package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
8 changes: 8 additions & 0 deletions scripts/copy-cjs-package-json.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Marks dist/cjs as CommonJS, overriding the root "type": "module".

import { copyFileSync } from 'node:fs';

copyFileSync(
new URL('./cjs-package.json', import.meta.url),
new URL('../dist/cjs/package.json', import.meta.url),
);
66 changes: 66 additions & 0 deletions scripts/test-package.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Packs the built library, installs the tarball into a throwaway consumer, and
// loads every `exports` entry point with both `require` and `import`.
// Expects `dist/` to be built already: `npm run test:package` does both.

import { execFileSync, spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url)));

const specifiers = Object.keys(pkg.exports).map((key) =>
key === '.' ? pkg.name : `${pkg.name}${key.slice(1)}`,
);

// The optional Mux peer is installed because the root and `/video-player`
// entry points load it unconditionally.
const peers = ['react', 'react-dom', '@mux/mux-player-react'].map(
(name) => `${name}@${pkg.devDependencies[name]}`,
);

/**
* Runs a command and returns its trimmed stdout, throwing if it exits non-zero.
*/
const run = (command, args, cwd) =>
execFileSync(command, args, { cwd, encoding: 'utf8', shell: process.platform === 'win32' }).trim();

/**
* Loads `specifier` in a fresh Node process from `cwd`, returning the error's
* first line, or `null` when it loads.
*/
const load = (cwd, specifier, mode) => {
const file = join(cwd, mode === 'require' ? 'load.cjs' : 'load.mjs');
writeFileSync(
file,
mode === 'require' ? `require(${JSON.stringify(specifier)});\n` : `await import(${JSON.stringify(specifier)});\n`,
);
const result = spawnSync(process.execPath, [file], { cwd, encoding: 'utf8' });
return result.status === 0 ? null : (result.stderr.match(/^\w*Error.*$/m)?.[0] ?? result.stderr.trim());
};

const workDir = mkdtempSync(join(tmpdir(), 'react-datocms-package-'));

try {
const tarball = join(workDir, run('npm', ['pack', '--ignore-scripts', '--silent', '--pack-destination', workDir]));

const consumerDir = join(workDir, 'consumer');
mkdirSync(consumerDir);
writeFileSync(join(consumerDir, 'package.json'), JSON.stringify({ name: 'consumer', private: true }));
run('npm', ['install', '--silent', '--no-audit', '--no-fund', tarball, ...peers], consumerDir);

const failures = specifiers.flatMap((specifier) =>
['require', 'import'].flatMap((mode) => {
const error = load(consumerDir, specifier, mode);
console.log(`${error ? 'FAIL' : 'ok '} ${mode} ${specifier}${error ? `: ${error}` : ''}`);
return error ? [specifier] : [];
}),
);

console.log(
`\nNode ${process.version}: ${specifiers.length * 2 - failures.length}/${specifiers.length * 2} entry point loads succeeded`,
);
process.exitCode = failures.length ? 1 : 0;
} finally {
rmSync(workDir, { recursive: true, force: true });
}
Loading