Skip to content

Commit

Permalink
Inline process.env variable references directly when installing. (#1044)
Browse files Browse the repository at this point in the history
* Inline process.env variable references directly when installing.

* Fix compatibility with old versions of Node.

* Use JSON.stringify on process.env replacement values.

* Extract env-mangling functions to improve readability.
  • Loading branch information
pkaminski authored Sep 12, 2020
1 parent 4632be7 commit 2926370
Show file tree
Hide file tree
Showing 7 changed files with 147 additions and 702 deletions.
1 change: 1 addition & 0 deletions snowpack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"@rollup/plugin-inject": "^4.0.2",
"@rollup/plugin-json": "^4.0.0",
"@rollup/plugin-node-resolve": "^9.0.0",
"@rollup/plugin-replace": "^2.3.3",
"@snowpack/plugin-build-script": "^2.0.6",
"@snowpack/plugin-run-script": "^2.1.1",
"cacache": "^15.0.0",
Expand Down
30 changes: 25 additions & 5 deletions snowpack/src/commands/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import rollupPluginCommonjs, {RollupCommonJSOptions} from '@rollup/plugin-common
import rollupPluginJson from '@rollup/plugin-json';
import rollupPluginNodeResolve from '@rollup/plugin-node-resolve';
import rollupPluginNodePolyfills from 'rollup-plugin-node-polyfills';
import rollupPluginReplace from '@rollup/plugin-replace';
import {init as initESModuleLexer} from 'es-module-lexer';
import findUp from 'find-up';
import util from 'util';
Expand All @@ -29,6 +30,7 @@ import {printStats} from '../stats-formatter.js';
import {
CommandOptions,
DependencyStatsOutput,
EnvVarReplacements,
ImportMap,
InstallTarget,
SnowpackConfig,
Expand Down Expand Up @@ -201,6 +203,24 @@ function resolveWebDependency(dep: string): DependencyLoc {
}
}

function generateEnvObject(userEnv: EnvVarReplacements) : Object {
return {
NODE_ENV: process.env.NODE_ENV || 'production',
...Object.keys(userEnv).reduce((acc, key) => {
const value = userEnv[key];
acc[key] = value === true ? process.env[key] : value;
return acc;
}, {})
};
}

function generateEnvReplacements(env: Object) : {[key: string]: string} {
return Object.keys(env).reduce((acc, key) => {
acc[`process.env.${key}`] = JSON.stringify(env[key]);
return acc;
}, {});
}

interface InstallOptions {
lockfile: ImportMap | null;
config: SnowpackConfig;
Expand All @@ -226,13 +246,15 @@ export async function install(
dest: destLoc,
externalPackage: externalPackages,
sourceMap,
env,
env: userEnv,
rollup: userDefinedRollup,
treeshake: isTreeshake,
polyfillNode,
},
} = config;

const env = generateEnvObject(userEnv);

const nodeModulesInstalled = findUp.sync('node_modules', {cwd, type: 'directory'});
if (!webDependencies && !(process.versions as any).pnp && !nodeModulesInstalled) {
logger.error('No "node_modules" directory exists. Did you run "npm install" first?');
Expand Down Expand Up @@ -342,17 +364,15 @@ ${colors.dim(
namedExports: true,
}),
rollupPluginCss(),
rollupPluginReplace(generateEnvReplacements(env)),
rollupPluginCommonjs({
extensions: ['.js', '.cjs'],
externalEsm: process.env.EXTERNAL_ESM_PACKAGES || [],
requireReturnsDefault: 'auto',
} as RollupCommonJSOptions),
rollupPluginWrapInstallTargets(!!isTreeshake, autoDetectNamedExports, installTargets),
rollupPluginDependencyStats((info) => (dependencyStats = info)),
rollupPluginNodeProcessPolyfill({
NODE_ENV: process.env.NODE_ENV || 'production',
...env,
}),
rollupPluginNodeProcessPolyfill(env),
polyfillNode && rollupPluginNodePolyfills(),
...userDefinedRollup.plugins, // load user-defined plugins last
rollupPluginCatchUnresolved(),
Expand Down
16 changes: 2 additions & 14 deletions snowpack/src/rollup-plugins/rollup-plugin-node-process-polyfill.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import inject from '@rollup/plugin-inject';
import {Plugin} from 'rollup';
import {EnvVarReplacements} from '../types/snowpack';
import generateProcessPolyfill from './generateProcessPolyfill';

const PROCESS_MODULE_NAME = 'process';
export function rollupPluginNodeProcessPolyfill(vars: EnvVarReplacements = {}): Plugin {
export function rollupPluginNodeProcessPolyfill(env = {}): Plugin {
const injectPlugin = inject({
process: PROCESS_MODULE_NAME,
});
Expand All @@ -21,21 +20,10 @@ export function rollupPluginNodeProcessPolyfill(vars: EnvVarReplacements = {}):
},
load(id) {
if (id === PROCESS_MODULE_NAME) {
return createProcessPolyfill(vars);
return {code: generateProcessPolyfill(env), moduleSideEffects: false};
}

return null;
},
};
}

function createProcessPolyfill(vars: EnvVarReplacements = {}) {
const env = Object.keys(vars).reduce((acc, id) => {
return {
...acc,
[id]: vars[id] === true ? process.env[id] : vars[id],
};
}, {});

return {code: generateProcessPolyfill(env), moduleSideEffects: false};
}
10 changes: 10 additions & 0 deletions test/build/__snapshots__/build.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -4631,6 +4631,11 @@ exports[`snowpack build package-tippy-js: web_modules/import-map.json 1`] = `

exports[`snowpack build package-tippy-js: web_modules/tippyjs.js 1`] = `
"import { c as createPopper } from './common/popper-XXXXXXXX.js';
/**!
* tippy.js v6.2.6
* (c) 2017-2020 atomiks
* MIT License
*/
var BOX_CLASS = \\"tippy-box\\";
var CONTENT_CLASS = \\"tippy-content\\";
var BACKDROP_CLASS = \\"tippy-backdrop\\";
Expand Down Expand Up @@ -5966,6 +5971,11 @@ document.head.appendChild(styleEl);"

exports[`snowpack build package-tippy-js: web_modules/tippyjs/headless/dist/tippy-headless.esm.js 1`] = `
"import { c as createPopper } from '../../../common/popper-XXXXXXXX.js';
/**!
* tippy.js v6.2.6
* (c) 2017-2020 atomiks
* MIT License
*/
var ROUND_ARROW = '<svg width=\\"16\\" height=\\"6\\" xmlns=\\"http://www.w3.org/2000/svg\\"><path d=\\"M0 6s1.796-.013 4.67-3.615C5.851.9 6.93.006 8 0c1.07-.006 2.148.887 3.343 2.385C14.233 6.005 16 6 16 6H0z\\"></svg>';
var CONTENT_CLASS = \\"tippy-content\\";
var BACKDROP_CLASS = \\"tippy-backdrop\\";
Expand Down
Loading

1 comment on commit 2926370

@vercel
Copy link

@vercel vercel bot commented on 2926370 Sep 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.