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

Generate ESM functions for Netlify #6666

Merged
merged 7 commits into from
Sep 12, 2022
Merged
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
44 changes: 14 additions & 30 deletions packages/adapter-netlify/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'fs';
import { dirname, join, resolve, posix } from 'path';
import { fileURLToPath } from 'url';
import glob from 'tiny-glob/sync.js';
eduardoboucas marked this conversation as resolved.
Show resolved Hide resolved
import esbuild from 'esbuild';
import toml from '@iarna/toml';

Expand Down Expand Up @@ -66,18 +65,14 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
`\n\n/${builder.config.kit.appDir}/immutable/*\n cache-control: public\n cache-control: immutable\n cache-control: max-age=31536000\n`
);

// for esbuild, use ESM
// for zip-it-and-ship-it, use CJS until https://github.com/netlify/zip-it-and-ship-it/issues/750
const esm = netlify_config?.functions?.node_bundler === 'esbuild';

if (edge) {
if (split) {
throw new Error('Cannot use `split: true` alongside `edge: true`');
}

await generate_edge_functions({ builder });
} else {
await generate_lambda_functions({ builder, esm, split, publish });
await generate_lambda_functions({ builder, split, publish });
}
}
};
Expand Down Expand Up @@ -148,9 +143,8 @@ async function generate_edge_functions({ builder }) {
* @param {import('@sveltejs/kit').Builder} params.builder
* @param { string } params.publish
* @param { boolean } params.split
* @param { boolean } params.esm
*/
async function generate_lambda_functions({ builder, publish, split, esm }) {
async function generate_lambda_functions({ builder, publish, split }) {
builder.mkdirp('.netlify/functions-internal');

/** @type {string[]} */
Expand All @@ -160,19 +154,11 @@ async function generate_lambda_functions({ builder, publish, split, esm }) {
const replace = {
'0SERVER': './server/index.js' // digit prefix prevents CJS build from using this as a variable name, which would also get replaced
};
if (esm) {
builder.copy(`${files}/esm`, '.netlify', { replace });
} else {
glob('**/*.js', { cwd: '.netlify/server', filesOnly: true }).forEach((file) => {
const filepath = `.netlify/server/${file}`;
const input = readFileSync(filepath, 'utf8');
const output = esbuild.transformSync(input, { format: 'cjs', target: 'node12' }).code;
writeFileSync(filepath, output);
});

builder.copy(`${files}/cjs`, '.netlify', { replace });
writeFileSync(join('.netlify', 'package.json'), JSON.stringify({ type: 'commonjs' }));
}
builder.copy(`${files}/esm`, '.netlify', { replace });

// Configuring the function to use ESM as the output format.
const fn_config = JSON.stringify({ config: { nodeModuleFormat: 'esm' }, version: 1 });

if (split) {
builder.log.minor('Generating serverless functions...');
Expand Down Expand Up @@ -201,14 +187,13 @@ async function generate_lambda_functions({ builder, publish, split, esm }) {
complete: (entry) => {
const manifest = entry.generateManifest({
relativePath: '../server',
format: esm ? 'esm' : 'cjs'
format: 'esm'
});

const fn = esm
? `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`
: `const { init } = require('../serverless.js');\n\nexports.handler = init(${manifest});\n`;
const fn = `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`;

writeFileSync(`.netlify/functions-internal/${name}.js`, fn);
writeFileSync(`.netlify/functions-internal/${name}.mjs`, fn);
writeFileSync(`.netlify/functions-internal/${name}.json`, fn_config);

redirects.push(`${pattern} /.netlify/functions/${name} 200`);
redirects.push(`${pattern}/__data.js /.netlify/functions/${name} 200`);
Expand All @@ -220,14 +205,13 @@ async function generate_lambda_functions({ builder, publish, split, esm }) {

const manifest = builder.generateManifest({
relativePath: '../server',
format: esm ? 'esm' : 'cjs'
format: 'esm'
});

const fn = esm
? `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`
: `const { init } = require('../serverless.js');\n\nexports.handler = init(${manifest});\n`;
const fn = `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`;

writeFileSync('.netlify/functions-internal/render.js', fn);
writeFileSync(`.netlify/functions-internal/render.json`, fn_config);
writeFileSync('.netlify/functions-internal/render.mjs', fn);
redirects.push('* /.netlify/functions/render 200');
}

Expand Down
3 changes: 1 addition & 2 deletions packages/adapter-netlify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@
"dependencies": {
"@iarna/toml": "^2.2.5",
"esbuild": "^0.15.6",
"set-cookie-parser": "^2.4.8",
"tiny-glob": "^0.2.9"
"set-cookie-parser": "^2.4.8"
},
"devDependencies": {
"@netlify/functions": "^1.0.0",
Expand Down
2 changes: 0 additions & 2 deletions pnpm-lock.yaml

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