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

handle node-fetch, whatwg-fetch Node polyfills #547

Merged
merged 1 commit into from
Jun 28, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 8 additions & 6 deletions src/commands/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ import {InputOptions, OutputOptions, rollup, RollupError} from 'rollup';
import validatePackageName from 'validate-npm-package-name';
import {EnvVarReplacements, SnowpackConfig, SnowpackSourceFile} from '../config.js';
import {resolveTargetsFromRemoteCDN} from '../resolve-remote.js';
import {rollupPluginCatchUnresolved} from '../rollup-plugin-catch-unresolved.js';
import {rollupPluginCss} from '../rollup-plugin-css';
import {rollupPluginEntrypointAlias} from '../rollup-plugin-entrypoint-alias.js';
import {rollupPluginDependencyCache} from '../rollup-plugin-remote-cdn.js';
import {DependencyStatsOutput, rollupPluginDependencyStats} from '../rollup-plugin-stats.js';
import {rollupPluginWrapInstallTargets} from '../rollup-plugin-wrap-install-targets';
import {rollupPluginCatchUnresolved} from '../rollup-plugins/rollup-plugin-catch-unresolved.js';
import {rollupPluginCatchFetch} from '../rollup-plugins/rollup-plugin-catch-fetch';
import {rollupPluginCss} from '../rollup-plugins/rollup-plugin-css';
import {rollupPluginEntrypointAlias} from '../rollup-plugins/rollup-plugin-entrypoint-alias.js';
import {rollupPluginDependencyCache} from '../rollup-plugins/rollup-plugin-remote-cdn.js';
import {DependencyStatsOutput, rollupPluginDependencyStats} from '../rollup-plugins/rollup-plugin-stats.js';
import {rollupPluginWrapInstallTargets} from '../rollup-plugins/rollup-plugin-wrap-install-targets';
import {InstallTarget, scanDepList, scanImports, scanImportsFromFiles} from '../scan-imports.js';
import {printStats} from '../stats-formatter.js';
import {
Expand Down Expand Up @@ -385,6 +386,7 @@ export async function install(
replacement: mod,
})),
}),
rollupPluginCatchFetch(),
rollupPluginNodeResolve({
mainFields: ['browser:module', 'module', 'browser', 'main'].filter(isTruthy),
extensions: ['.mjs', '.cjs', '.js', '.json'], // Default: [ '.mjs', '.js', '.json', '.node' ]
Expand Down
45 changes: 45 additions & 0 deletions src/rollup-plugins/rollup-plugin-catch-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {Plugin} from 'rollup';

const FETCH_POLYFILL = `
// native patch for: node-fetch, whatwg-fetch
// ref: https://github.com/tc39/proposal-global
var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
}
var global = getGlobal();
export default global.fetch.bind(global);
export const Headers = global.Headers;
export const Request = global.Request;
export const Response = global.Response;
`;

/**
* rollup-plugin-catch-fetch
*
* How it works: NPM packages will sometimes contain Node.js-specific polyfills
* for the native browser Fetch API. Since this makes no sense in an ESM web
* project, we can replace these expensive polyfills with native references to
* the fetch API.
*
* This still allows you to polyfill fetch in older browsers, if you desire.
*/
export function rollupPluginCatchFetch(): Plugin {
return {
name: 'snowpack:fetch-handler',
resolveId(id) {
if (id !== 'node-fetch' && id !== 'whatwg-fetch') {
return null;
}
return id;
},
load(id) {
if (id !== 'node-fetch' && id !== 'whatwg-fetch') {
return null;
}
return FETCH_POLYFILL;
},
};
}
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path from 'path';
import {Plugin} from 'rollup';
import {resolveDependencyManifest} from './util';
import {resolveDependencyManifest} from '../util';

const IS_DEEP_PACKAGE_IMPORT = /^(@[\w-]+\/)?([\w-]+)\/(.*)/;
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import path from 'path';
import {OutputOptions, Plugin, ResolvedId} from 'rollup';
import tar from 'tar';
import url from 'url';
import {fetchCDNResource, HAS_CDN_HASH_REGEX, PIKA_CDN, RESOURCE_CACHE} from './util';
import {fetchCDNResource, HAS_CDN_HASH_REGEX, PIKA_CDN, RESOURCE_CACHE} from '../util';

const CACHED_FILE_ID_PREFIX = 'snowpack-pkg-cache:';
const PIKA_CDN_TRIM_LENGTH = PIKA_CDN.length;
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as colors from 'kleur/colors';
import path from 'path';
import {Plugin} from 'rollup';
import {InstallTarget} from './scan-imports';
import {InstallTarget} from '../scan-imports';

function autoDetectExports(fileLoc: string): string[] | undefined {
try {
Expand Down
2 changes: 1 addition & 1 deletion src/stats-formatter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as colors from 'kleur/colors';
import {DependencyStats, DependencyStatsOutput} from './rollup-plugin-stats';
import {DependencyStats, DependencyStatsOutput} from './rollup-plugins/rollup-plugin-stats';

/** The minimum width, in characters, of each size column */
const SIZE_COLUMN_WIDTH = 11;
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"imports": {
"mock-test-package-a": "./mock-test-package-a.js"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// native patch for: node-fetch, whatwg-fetch
// ref: https://github.com/tc39/proposal-global
var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};
var global = getGlobal();
var nodeFetch = global.fetch.bind(global);
const Headers = global.Headers;
const Request = global.Request;
const Response = global.Response;

var fetch = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': nodeFetch,
Headers: Headers,
Request: Request,
Response: Response
});

// native patch for: node-fetch, whatwg-fetch
// ref: https://github.com/tc39/proposal-global
var getGlobal$1 = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global$1 !== 'undefined') { return global$1; }
throw new Error('unable to locate global object');
};
var global$1 = getGlobal$1();
var whatwgFetch = global$1.fetch.bind(global$1);
const Headers$1 = global$1.Headers;
const Request$1 = global$1.Request;
const Response$1 = global$1.Response;

var fetch_ = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': whatwgFetch,
Headers: Headers$1,
Request: Request$1,
Response: Response$1
});

console.log(fetch, fetch_);
3 changes: 3 additions & 0 deletions test/integration/dep-node-fetch/expected-output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
✔ snowpack install complete.
⦿ web_modules/ size gzip brotli
└─ mock-test-package-a.js XXXX KB XXXX KB XXXX KB

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

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

12 changes: 12 additions & 0 deletions test/integration/dep-node-fetch/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"description": "Handle specific node.js fetch polyfill packages",
"scripts": {
"TEST": "node ../../../pkg/dist-node/index.bin.js"
},
"snowpack": {
"install": ["mock-test-package-a"]
},
"dependencies": {
"mock-test-package-a": "^1.0.0"
}
}