Skip to content

Commit

Permalink
new: Add custom Babel plugin to transform environment expressions. (#17)
Browse files Browse the repository at this point in the history
* Add plugin.

* Add types.

* Add temp packemon script.
  • Loading branch information
milesj authored Dec 29, 2020
1 parent b36a332 commit f9f03bd
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 12 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"type": "beemo typescript --noEmit",
"prerelease": "yarn run ci && yarn run setup && yarn run pack",
"pack": "NODE_ENV=production yarn run packemon pack --addEngines --generateDeclaration=api",
"packemon": "node ./build/bin.js"
"packemon": "node ./packemon.js"
},
"repository": "https://github.com/milesj/packemon.git",
"author": "Miles Johnson",
Expand Down Expand Up @@ -85,7 +85,6 @@
"@rollup/plugin-commonjs": "^17.0.0",
"@rollup/plugin-node-resolve": "^11.0.1",
"babel-plugin-transform-async-to-promises": "^0.8.15",
"babel-plugin-transform-dev": "^2.0.1",
"builtin-modules": "^3.2.0",
"chokidar": "^3.4.3",
"execa": "^5.0.0",
Expand Down
7 changes: 7 additions & 0 deletions packemon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* eslint-disable no-underscore-dangle */

global.__DEV__ = true;
global.__PROD__ = false;
global.__TEST__ = false;

require('./build/bin');
2 changes: 1 addition & 1 deletion src/TypesArtifact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export default class TypesArtifact extends Artifact<TypesBuild> {

// Extract all DTS into a single file
const result = Extractor.invoke(ExtractorConfig.loadFileAndPrepare(configPath), {
localBuild: process.env.NODE_ENV !== 'production',
localBuild: __DEV__,
messageCallback: (warn) => {
// eslint-disable-next-line no-param-reassign
warn.handled = true;
Expand Down
14 changes: 7 additions & 7 deletions src/babel/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { PluginItem, TransformOptions as ConfigStructure } from '@babel/core';
import { BROWSER_TARGETS, NATIVE_TARGETS, NODE_SUPPORTED_VERSIONS } from '../constants';
import { Support, Format, Platform, FeatureFlags, BundleBuild } from '../types';
import BundleArtifact from '../BundleArtifact';
import envExpressionsPlugin from './plugins/envExpressions';

// https://babeljs.io/docs/en/babel-preset-env
export interface PresetEnvOptions {
Expand Down Expand Up @@ -62,7 +63,7 @@ function getPlatformEnvOptions(
],
modules,
targets: {
node: process.env.NODE_ENV === 'test' ? 'current' : NODE_SUPPORTED_VERSIONS[support],
node: __TEST__ ? 'current' : NODE_SUPPORTED_VERSIONS[support],
},
};

Expand Down Expand Up @@ -132,7 +133,7 @@ export function getBabelInputConfig(
presets.push([
resolve('@babel/preset-react'),
{
development: process.env.NODE_ENV !== 'production',
development: __DEV__,
throwIfNamespace: true,
},
]);
Expand All @@ -150,14 +151,13 @@ export function getBabelOutputConfig(
const plugins: PluginItem[] = [];
const presets: PluginItem[] = [];
const isFuture = support !== 'legacy' && support !== 'stable';
const isProd = process.env.NODE_ENV === 'production';

// ENVIRONMENT

const envOptions: PresetEnvOptions = {
// Prefer speed and smaller filesize in prod
spec: !isProd,
loose: isProd,
spec: __DEV__,
loose: __PROD__,
// Consumers must polyfill accordingly
useBuiltIns: false,
// Transform features accordingly
Expand Down Expand Up @@ -188,8 +188,8 @@ export function getBabelOutputConfig(
]);
}

// Support `__DEV__` shortcuts
plugins.push([resolve('babel-plugin-transform-dev'), { evaluate: false }]);
// Support env expression shortcuts
plugins.push(envExpressionsPlugin());

return getSharedConfig(plugins, presets, features);
}
53 changes: 53 additions & 0 deletions src/babel/plugins/envExpressions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { types as t, NodePath } from '@babel/core';

const exprs = {
__DEV__: ['!==', 'production'],
__PROD__: ['===', 'production'],
__TEST__: ['===', 'test'],
};

export default function envExpressions() {
return {
visitor: {
Identifier: {
enter(path: NodePath<t.Identifier>) {
Object.entries(exprs).forEach(([expr, [op, env]]) => {
if (
path.isIdentifier({ name: expr }) &&
// const __DEV__ = var;
!path.parentPath.isVariableDeclarator() &&
// { __DEV__: var }
!path.parentPath.isObjectProperty() &&
// obj.__DEV__ = var;
!path.parentPath.isMemberExpression()
// // if (__DEV__)
// (path.parentPath.isIfStatement() ||
// // switch(__DEV__)
// path.parentPath.isSwitchStatement() ||
// // __DEV__ && var
// path.parentPath.isLogicalExpression() ||
// // __DEV__ ? a : b
// path.parentPath.isConditionalExpression() ||
// // !__DEV__
// path.parentPath.isUnaryExpression() ||
// // prop={__DEV__}
// path.parentPath.isJSXExpressionContainer())
) {
path.replaceWith(
t.binaryExpression(
op as '===',
t.memberExpression(
t.memberExpression(t.identifier('process'), t.identifier('env'), false),
t.identifier('NODE_ENV'),
false,
),
t.stringLiteral(env),
),
);
}
});
},
},
},
};
}
8 changes: 8 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
/* eslint-disable no-underscore-dangle */

import ts from 'typescript';
import { PackageStructure } from '@boost/common';

declare global {
const __DEV__: boolean;
const __PROD__: boolean;
const __TEST__: boolean;
}

export type Platform = 'browser' | 'native' | 'node'; // electron

export type Support =
Expand Down
5 changes: 3 additions & 2 deletions website/docs/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,9 @@ The following plugins are enabled when one of their conditions are met.
- `babel-plugin-transform-async-to-promises`
- Enabled when package [platform](./config.md#platforms) is configured to `browser`. This attempts
to _avoid_ `regenerator-runtime` by transforming async/await to promises.
- `babel-plugin-transform-dev`
- Always enabled. Will transform `__DEV__` to `process.env.NODE_ENV` conditionals.
- _Custom_
- Always enabled. Will transform `__DEV__`, `__PROD__`, and `__TEST__` to `process.env.NODE_ENV`
conditionals.

## Rollup configuration

Expand Down

0 comments on commit f9f03bd

Please sign in to comment.