Skip to content

Commit fadc3f2

Browse files
TooTallNateTimerkodiakhq[bot]
authored
[next][node][static-build] Execute "vercel-build" script if defined (vercel#4863)
* [build-utils] Make `runPackageJsonScript()` run the `vercel-` or `now-` if defined in `package.json` * [build-utils] Export `getScriptName()` * [next] Use `getScriptName()` and `remove()` * [node] Update for `vercel-` * [static-build] Update for `vercel-` * Remove debug * Add `getScriptName()` unit tests * Test for `vercel-build` in e2e * Make platform name behavior be opt-in So that it's not a breaking behavior change. * Check for only "vercel-build" or "now-build", but not "build" * Simplify `getScriptName()` to return the first existing script in a possible set * Revert change * Fix test Co-authored-by: Joe Haddad <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
1 parent a1d548d commit fadc3f2

File tree

8 files changed

+48
-64
lines changed

8 files changed

+48
-64
lines changed

packages/now-next/src/index.ts

+28-51
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const {
77
getLambdaOptionsFromFunction,
88
getNodeVersion,
99
getSpawnOptions,
10+
getScriptName,
1011
glob,
1112
runNpmInstall,
1213
runPackageJsonScript,
@@ -35,13 +36,7 @@ import {
3536
import { nodeFileTrace, NodeFileTraceReasons } from '@zeit/node-file-trace';
3637
import { ChildProcess, fork } from 'child_process';
3738
import escapeStringRegexp from 'escape-string-regexp';
38-
import {
39-
lstat,
40-
pathExists,
41-
readFile,
42-
unlink as unlinkFile,
43-
writeFile,
44-
} from 'fs-extra';
39+
import { lstat, pathExists, readFile, remove, writeFile } from 'fs-extra';
4540
import os from 'os';
4641
import path from 'path';
4742
import resolveFrom from 'resolve-from';
@@ -108,13 +103,7 @@ const MAX_AGE_ONE_YEAR = 31536000;
108103
/**
109104
* Read package.json from files
110105
*/
111-
async function readPackageJson(
112-
entryPath: string
113-
): Promise<{
114-
scripts?: { [key: string]: string };
115-
dependencies?: { [key: string]: string };
116-
devDependencies?: { [key: string]: string };
117-
}> {
106+
async function readPackageJson(entryPath: string): Promise<PackageJson> {
118107
const packagePath = path.join(entryPath, 'package.json');
119108

120109
try {
@@ -329,49 +318,38 @@ export const build = async ({
329318
}
330319

331320
const isLegacy = nextVersionRange && isLegacyNext(nextVersionRange);
332-
let shouldRunScript = 'now-build';
333-
334321
debug(`MODE: ${isLegacy ? 'legacy' : 'serverless'}`);
335322

336323
if (isLegacy) {
337-
try {
338-
await unlinkFile(path.join(entryPath, 'yarn.lock'));
339-
} catch (err) {
340-
debug('no yarn.lock removed');
341-
}
342-
343-
try {
344-
await unlinkFile(path.join(entryPath, 'package-lock.json'));
345-
} catch (err) {
346-
debug('no package-lock.json removed');
347-
}
348-
349324
console.warn(
350325
"WARNING: your application is being deployed in @vercel/next's legacy mode. http://err.sh/vercel/vercel/now-next-legacy-mode"
351326
);
352327

328+
await Promise.all([
329+
remove(path.join(entryPath, 'yarn.lock')),
330+
remove(path.join(entryPath, 'package-lock.json')),
331+
]);
332+
353333
debug('Normalizing package.json');
354334
const packageJson = normalizePackageJson(pkg);
355335
debug('Normalized package.json result: ', packageJson);
356336
await writePackageJson(entryPath, packageJson);
357-
} else if (pkg.scripts && pkg.scripts['now-build']) {
358-
debug('Found user `now-build` script');
359-
shouldRunScript = 'now-build';
360-
} else if (pkg.scripts && pkg.scripts['build']) {
361-
debug('Found user `build` script');
362-
shouldRunScript = 'build';
363-
} else if (!pkg.scripts || !pkg.scripts['now-build']) {
364-
debug(
337+
}
338+
339+
const buildScriptName = getScriptName(pkg, [
340+
'vercel-build',
341+
'now-build',
342+
'build',
343+
]);
344+
let { buildCommand } = config;
345+
346+
if (!buildScriptName && !buildCommand) {
347+
console.log(
365348
'Your application is being built using `next build`. ' +
366-
'If you need to define a different build step, please create a `now-build` script in your `package.json` ' +
367-
'(e.g. `{ "scripts": { "now-build": "npm run prepare && next build" } }`).'
349+
'If you need to define a different build step, please create a `vercel-build` script in your `package.json` ' +
350+
'(e.g. `{ "scripts": { "vercel-build": "npm run prepare && next build" } }`).'
368351
);
369-
pkg.scripts = {
370-
'now-build': 'next build',
371-
...(pkg.scripts || {}),
372-
};
373-
shouldRunScript = 'now-build';
374-
await writePackageJson(entryPath, pkg);
352+
buildCommand = 'next build';
375353
}
376354

377355
if (process.env.NPM_AUTH_TOKEN) {
@@ -398,12 +376,11 @@ export const build = async ({
398376
await createServerlessConfig(workPath, entryPath, nextVersion);
399377
}
400378

401-
debug('Running user script...');
402379
const memoryToConsume = Math.floor(os.totalmem() / 1024 ** 2) - 128;
403380
const env: { [key: string]: string | undefined } = { ...spawnOpts.env };
404381
env.NODE_OPTIONS = `--max_old_space_size=${memoryToConsume}`;
405382

406-
if (config.buildCommand) {
383+
if (buildCommand) {
407384
// Add `node_modules/.bin` to PATH
408385
const nodeBinPath = await getNodeBinPath({ cwd: entryPath });
409386
env.PATH = `${nodeBinPath}${path.delimiter}${env.PATH}`;
@@ -412,14 +389,14 @@ export const build = async ({
412389
`Added "${nodeBinPath}" to PATH env because a build command was used.`
413390
);
414391

415-
console.log(`Running "${config.buildCommand}"`);
416-
await execCommand(config.buildCommand, {
392+
console.log(`Running "${buildCommand}"`);
393+
await execCommand(buildCommand, {
417394
...spawnOpts,
418395
cwd: entryPath,
419396
env,
420397
});
421-
} else {
422-
await runPackageJsonScript(entryPath, shouldRunScript, {
398+
} else if (buildScriptName) {
399+
await runPackageJsonScript(entryPath, buildScriptName, {
423400
...spawnOpts,
424401
env,
425402
});
@@ -667,7 +644,7 @@ export const build = async ({
667644
}
668645

669646
if (process.env.NPM_AUTH_TOKEN) {
670-
await unlinkFile(path.join(entryPath, '.npmrc'));
647+
await remove(path.join(entryPath, '.npmrc'));
671648
}
672649

673650
const pageLambdaRoutes: Route[] = [];

packages/now-next/test/fixtures/10-export-cache-headers/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"scripts": {
3-
"build": "next build && next export"
3+
"now-build": "next build && next export"
44
},
55
"dependencies": {
66
"next": "canary",

packages/now-next/test/fixtures/11-export-clean-urls/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"scripts": {
3-
"build": "next build && next export"
3+
"vercel-build": "next build && next export"
44
},
55
"dependencies": {
66
"next": "canary",

packages/now-node/src/index.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -361,10 +361,12 @@ export async function build({
361361
meta,
362362
});
363363

364-
debug('Running user script...');
365-
const runScriptTime = Date.now();
366-
await runPackageJsonScript(entrypointFsDirname, 'now-build', spawnOpts);
367-
debug(`Script complete [${Date.now() - runScriptTime}ms]`);
364+
await runPackageJsonScript(
365+
entrypointFsDirname,
366+
// Don't consider "build" script since its intended for frontend code
367+
['vercel-build', 'now-build'],
368+
spawnOpts
369+
);
368370

369371
debug('Tracing input files...');
370372
const traceTime = Date.now();

packages/now-static-build/build.sh

+4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
#!/bin/bash
22
set -euo pipefail
33

4+
# Start fresh
5+
rm -rf dist
6+
7+
# Build with `ncc`
48
ncc build src/index.ts -e @vercel/build-utils -e @now/build-utils -o dist

packages/now-static-build/src/index.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,6 @@ export async function build({
264264
const pkg = getPkg(entrypoint, workPath);
265265

266266
const devScript = pkg ? getScriptName(pkg, 'dev', config) : null;
267-
const buildScript = pkg ? getScriptName(pkg, 'build', config) : null;
268267

269268
const framework = getFramework(config, pkg);
270269

@@ -431,8 +430,6 @@ export async function build({
431430

432431
if (buildCommand) {
433432
debug(`Executing "${buildCommand}"`);
434-
} else {
435-
debug(`Running "${buildScript}" in "${entrypoint}"`);
436433
}
437434

438435
const found =
@@ -441,12 +438,16 @@ export async function build({
441438
...spawnOpts,
442439
cwd: entrypointDir,
443440
})
444-
: await runPackageJsonScript(entrypointDir, buildScript!, spawnOpts);
441+
: await runPackageJsonScript(
442+
entrypointDir,
443+
['vercel-build', 'now-build', 'build'],
444+
spawnOpts
445+
);
445446

446447
if (!found) {
447448
throw new Error(
448449
`Missing required "${
449-
buildCommand || buildScript
450+
buildCommand || 'vercel-build'
450451
}" script in "${entrypoint}"`
451452
);
452453
}
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"scripts": {
3-
"now-build": "mkdir dist && node build.js"
3+
"vercel-build": "mkdir dist && node build.js"
44
}
55
}

packages/now-static-build/test/integration.test.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ const testsThatFailToBuild = new Map([
3535
['05-empty-dist-dir', 'The Output Directory "dist" is empty.'],
3636
[
3737
'06-missing-script',
38-
'Missing required "now-build" script in "package.json"',
38+
'Missing required "vercel-build" script in "package.json"',
3939
],
4040
['07-nonzero-sh', 'Command "./build.sh" exited with 1'],
4141
[

0 commit comments

Comments
 (0)