Skip to content

Commit

Permalink
Framework: ES Modules + Tree Shaking (Automattic#16057)
Browse files Browse the repository at this point in the history
* Build: disable commonjs transform + add-module-exports

* Prefer import to require, and require.default where necessary

Background info:

in es6-land and webpack, if you want to require something that is exported in an es6 fashion, you need to write this:
require( 'module' ).default.

The default is not assumed.  Named imports work as expected and you write
require( 'module' ).namedExport.  So in a sense, default is just another name.

This PR is about converting as many requires into imports as possible because that makes everything less confusing and increases the scope of what webpack can statically analyze.

The only situations in which it is advisable to let a require stick around, is when it is only conditionally imported based on NODE_ENV.

* sections-middleware require.default

* Extensions: es6modules compatibility

This one is a bit tricky because of how its used both on the client and the
server where there is varying levels of `import` support.

In order to compensate, I map all of the reducer functions to fn.default on boot in the client.

* Fix test

* debugFactory fix

* address 'this' issue within client/lib/posts

* fix getPagePath

* :headbandage: :headbang: thanks @jsnajdr

* simplify getPagePath
  • Loading branch information
samouri authored Jan 24, 2018
1 parent c392b97 commit 2f082a9
Show file tree
Hide file tree
Showing 36 changed files with 186 additions and 167 deletions.
5 changes: 2 additions & 3 deletions .babelrc
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,14 @@
"kebabCase": true
}
}
],
"./inline-imports.js"
]
],
"env": {
"test": {
"plugins": [
[ "transform-builtin-extend", {
"globals": [ "Error" ]
} ],
} ]
]
}
}
Expand Down
2 changes: 1 addition & 1 deletion client/boot/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import './polyfills';

if ( process.env.NODE_ENV === 'development' ) {
require( 'lib/wrap-es6-functions' )();
require( 'lib/wrap-es6-functions' ).default();
}

/**
Expand Down
11 changes: 7 additions & 4 deletions client/boot/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ import { setLocale, setLocaleRawData } from 'state/ui/language/actions';
import { setCurrentUserOnReduxStore } from 'lib/redux-helpers';
import { installPerfmonPageHandlers } from 'lib/perfmon';
import { getSections, setupRoutes } from 'sections-middleware';
import { checkFormHandler } from 'lib/protect-form';
import notices from 'notices';
import authController from 'auth/controller';

const debug = debugFactory( 'calypso' );

Expand Down Expand Up @@ -112,7 +115,7 @@ const loggedOutMiddleware = currentUser => {
const oauthTokenMiddleware = () => {
if ( config.isEnabled( 'oauth' ) ) {
// Forces OAuth users to the /login page if no token is present
page( '*', require( 'auth/controller' ).checkToken );
page( '*', authController.checkToken );
}
};

Expand All @@ -126,12 +129,12 @@ const setRouteMiddleware = () => {

const clearNoticesMiddleware = () => {
//TODO: remove this one when notices are reduxified - it is for old notices
page( '*', require( 'notices' ).clearNoticesOnNavigation );
page( '*', notices.clearNoticesOnNavigation );
};

const unsavedFormsMiddleware = () => {
// warn against navigating from changed, unsaved forms
page.exit( '*', require( 'lib/protect-form' ).checkFormHandler );
page.exit( '*', checkFormHandler );
};

export const locales = ( currentUser, reduxStore ) => {
Expand All @@ -156,7 +159,7 @@ export const utils = () => {
debug( 'Executing Calypso utils.' );

if ( process.env.NODE_ENV === 'development' ) {
require( './dev-modules' )();
require( './dev-modules' ).default();
}

// Infer touch screen by checking if device supports touch events
Expand Down
13 changes: 8 additions & 5 deletions client/boot/project/wordpress-com.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ import { pruneStaleRecords } from 'lib/wp/sync-handler';
import { setReduxStore as setSupportUserReduxStore } from 'lib/user/support-user-interop';
import { getSelectedSiteId, getSectionName } from 'state/ui/selectors';
import { setNextLayoutFocus, activateNextLayoutFocus } from 'state/ui/layout-focus/actions';
import Logger from 'lib/catch-js-errors';
import setupMySitesRoute from 'my-sites';
import setupGlobalKeyboardShortcuts from 'lib/keyboard-shortcuts/global';
import * as controller from 'controller';

const debug = debugFactory( 'calypso' );

function renderLayout( reduxStore ) {
const Layout = require( 'controller' ).ReduxWrappedLayout;
const Layout = controller.ReduxWrappedLayout;

const layoutElement = React.createElement( Layout, {
store: reduxStore,
Expand Down Expand Up @@ -89,7 +93,6 @@ export function setupMiddlewares( currentUser, reduxStore ) {
renderLayout( reduxStore );

if ( config.isEnabled( 'catch-js-errors' ) ) {
const Logger = require( 'lib/catch-js-errors' );
const errorLogger = new Logger();
//Save errorLogger to a singleton for use in arbitrary logging.
require( 'lib/catch-js-errors/log' ).registerLogger( errorLogger );
Expand Down Expand Up @@ -207,7 +210,7 @@ export function setupMiddlewares( currentUser, reduxStore ) {
} );
}

require( 'my-sites' )();
setupMySitesRoute();

const state = reduxStore.getState();
if ( config.isEnabled( 'happychat' ) ) {
Expand All @@ -218,11 +221,11 @@ export function setupMiddlewares( currentUser, reduxStore ) {
}

if ( config.isEnabled( 'keyboard-shortcuts' ) ) {
require( 'lib/keyboard-shortcuts/global' )();
setupGlobalKeyboardShortcuts();
}

if ( config.isEnabled( 'desktop' ) ) {
require( 'lib/desktop' ).init();
require( 'lib/desktop' ).default.init();
}

if ( config.isEnabled( 'rubberband-scroll-disable' ) ) {
Expand Down
11 changes: 2 additions & 9 deletions client/layout/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ import QueryPreferences from 'components/data/query-preferences';
/**
* Internal dependencies
*/
let KeyboardShortcutsMenu, SupportUser;

import PropTypes from 'prop-types';
import QuerySites from 'components/data/query-sites';
import { isOffline } from 'state/application/selectors';
Expand All @@ -51,14 +49,9 @@ import NpsSurveyNotice from 'layout/nps-survey-notice';
import AppBanner from 'blocks/app-banner';
import { getPreference } from 'state/preferences/selectors';
import JITM from 'blocks/jitm';
import KeyboardShortcutsMenu from 'lib/keyboard-shortcuts/menu';
import SupportUser from 'support/support-user';

if ( config.isEnabled( 'keyboard-shortcuts' ) ) {
KeyboardShortcutsMenu = require( 'lib/keyboard-shortcuts/menu' );
}

if ( config.isEnabled( 'support-user' ) ) {
SupportUser = require( 'support/support-user' );
}
/* eslint-disable react/no-deprecated */
const Layout = createReactClass( {
/* eslint-enable react/no-deprecated */
Expand Down
17 changes: 7 additions & 10 deletions client/lib/create-selector/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@
/**
* External dependencies
*/

import { memoize } from 'lodash';
import { memoize, includes } from 'lodash';
import shallowEqual from 'react-pure-render/shallowEqual';

/**
* Internal dependencies
*/
import warn from 'lib/warn';

/**
* Constants
*/
Expand Down Expand Up @@ -39,14 +43,7 @@ const DEFAULT_GET_DEPENDANTS = state => state;
* @type {Function} Function returning cache key for memoized selector
*/
const DEFAULT_GET_CACHE_KEY = ( () => {
let warn, includes;
if ( 'production' !== process.env.NODE_ENV ) {
// Webpack can optimize bundles if it can detect that a block will
// never be reached. Since `NODE_ENV` is defined using DefinePlugin,
// these debugging modules will be excluded from the production build.
warn = require( 'lib/warn' );
includes = require( 'lodash/includes' );
} else {
if ( 'production' === process.env.NODE_ENV ) {
return ( state, ...args ) => args.join();
}

Expand Down
3 changes: 2 additions & 1 deletion client/lib/happychat/connection-ng.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
import IO from 'socket.io-client';
import { isString } from 'lodash';
import debugFactory from 'debug';

/**
* Internal dependencies
Expand All @@ -23,7 +24,7 @@ import {
requestTranscript,
} from 'state/happychat/connection/actions';

const debug = require( 'debug' )( 'calypso:happychat:connection' );
const debug = debugFactory( 'calypso:happychat:connection' );

const buildConnection = socket =>
isString( socket )
Expand Down
3 changes: 2 additions & 1 deletion client/lib/happychat/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
import IO from 'socket.io-client';
import { isString } from 'lodash';
import debugFactory from 'debug';

/**
* Internal dependencies
Expand All @@ -23,7 +24,7 @@ import {
requestTranscript,
} from 'state/happychat/connection/actions';

const debug = require( 'debug' )( 'calypso:happychat:connection' );
const debug = debugFactory( 'calypso:happychat:connection' );

const buildConnection = socket =>
isString( socket )
Expand Down
3 changes: 2 additions & 1 deletion client/lib/importer/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

import Dispatcher from 'dispatcher';
import { flowRight, includes, partial } from 'lodash';
const wpcom = require( 'lib/wp' ).undocumented();
import wpLib from 'lib/wp';
const wpcom = wpLib.undocumented();

/**
* Internal dependencies
Expand Down
4 changes: 2 additions & 2 deletions client/lib/posts/post-list-cache-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import debugFactory from 'debug';
*/
import Dispatcher from 'dispatcher';
import { cacheIndex } from 'lib/wp/sync-handler/cache-index';
import PostListStoreFactory from './post-list-store-factory';

let cache = {};
const _canonicalCache = {};
Expand Down Expand Up @@ -114,8 +115,7 @@ function isListKeyFresh( listKey ) {

PostsListCache.dispatchToken = Dispatcher.register( function( payload ) {
var action = payload.action,
PostListStore = require( './post-list-store-factory' )();

PostListStore = PostListStoreFactory();
Dispatcher.waitFor( [ PostListStore.dispatchToken ] );

switch ( action.type ) {
Expand Down
50 changes: 25 additions & 25 deletions client/lib/posts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,18 @@ export const userCan = function( capability, post ) {
return hasCap;
};

export const isBackDatedPublished = function( post ) {
if ( ! post || post.status !== 'future' ) {
return false;
}

return moment( post.date ).isBefore( moment() );
};

export const isPublished = function( post ) {
return (
post &&
( post.status === 'publish' || post.status === 'private' || this.isBackDatedPublished( post ) )
( post.status === 'publish' || post.status === 'private' || isBackDatedPublished( post ) )
);
};

Expand All @@ -98,14 +106,6 @@ export const getEditedTime = function( post ) {
return post.modified;
};

export const isBackDatedPublished = function( post ) {
if ( ! post || post.status !== 'future' ) {
return false;
}

return moment( post.date ).isBefore( moment() );
};

export const isFutureDated = function( post ) {
if ( ! post ) {
return false;
Expand Down Expand Up @@ -171,6 +171,17 @@ export const normalizeAsync = function( post, callback ) {
postNormalizer( post, [ postNormalizer.keepValidImages( 72, 72 ) ], callback );
};

export const removeSlug = function( path ) {
if ( ! path ) {
return;
}

const pathParts = path.slice( 0, -1 ).split( '/' );
pathParts[ pathParts.length - 1 ] = '';

return pathParts.join( '/' );
};

export const getPermalinkBasePath = function( post ) {
if ( ! post ) {
return;
Expand All @@ -179,33 +190,22 @@ export const getPermalinkBasePath = function( post ) {
let path = post.URL;

// if we have a permalink_URL, utlize that
if ( ! this.isPublished( post ) && post.other_URLs && post.other_URLs.permalink_URL ) {
if ( ! isPublished( post ) && post.other_URLs && post.other_URLs.permalink_URL ) {
path = post.other_URLs.permalink_URL;
}

return this.removeSlug( path );
return removeSlug( path );
};

export const getPagePath = function( post ) {
if ( ! post ) {
return;
}
if ( ! this.isPublished( post ) ) {
return this.getPermalinkBasePath( post );
if ( ! isPublished( post ) ) {
return getPermalinkBasePath( post );
}

return this.removeSlug( post.URL );
};

export const removeSlug = function( path ) {
if ( ! path ) {
return;
}

const pathParts = path.slice( 0, -1 ).split( '/' );
pathParts[ pathParts.length - 1 ] = '';

return pathParts.join( '/' );
return removeSlug( post.URL );
};

/**
Expand Down
12 changes: 7 additions & 5 deletions client/lib/wp/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,23 @@ import config from 'config';
import wpcomSupport from 'lib/wp/support';
import { injectLocalization } from './localization';
import { injectGuestSandboxTicketHandler } from './handlers/guest-sandbox-ticket';
import * as oauthToken from 'lib/oauth-token';
import wpcomXhrWrapper from 'lib/wpcom-xhr-wrapper';
import wpcomProxyRequest from 'wpcom-proxy-request';

const addSyncHandlerWrapper = config.isEnabled( 'sync-handler' );
let wpcom;

if ( config.isEnabled( 'oauth' ) ) {
const oauthToken = require( 'lib/oauth-token' );
const requestHandler = addSyncHandlerWrapper
? new SyncHandler( require( 'lib/wpcom-xhr-wrapper' ) )
: require( 'lib/wpcom-xhr-wrapper' );
? new SyncHandler( wpcomXhrWrapper )
: wpcomXhrWrapper;

wpcom = wpcomUndocumented( oauthToken.getToken(), requestHandler );
} else {
const requestHandler = addSyncHandlerWrapper
? new SyncHandler( require( 'wpcom-proxy-request' ).default )
: require( 'wpcom-proxy-request' ).default;
? new SyncHandler( wpcomProxyRequest )
: wpcomProxyRequest;

wpcom = wpcomUndocumented( requestHandler );

Expand Down
6 changes: 4 additions & 2 deletions client/lib/wp/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
import wpcomUndocumented from 'lib/wpcom-undocumented';
import config from 'config';
import { injectLocalization } from './localization';
import wpSupportWrapper from 'lib/wp/support';
import wpcomXhrRequest from 'wpcom-xhr-request';

let wpcom = wpcomUndocumented( require( 'wpcom-xhr-request' ) );
let wpcom = wpcomUndocumented( wpcomXhrRequest );

if ( config.isEnabled( 'support-user' ) ) {
wpcom = require( 'lib/wp/support' )( wpcom );
wpcom = wpSupportWrapper( wpcom );
}

// Inject localization helpers to `wpcom` instance
Expand Down
4 changes: 2 additions & 2 deletions client/me/account/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ import i18n from 'i18n-calypso';
import analytics from 'lib/analytics';
import userSettings from 'lib/user-settings';
import { setDocumentHeadTitle as setTitle } from 'state/document-head/actions';
import AccountComponent from 'me/account/main';
import username from 'lib/username';

const ANALYTICS_PAGE_TITLE = 'Me';

export default {
account( context, next ) {
const AccountComponent = require( 'me/account/main' );
const username = require( 'lib/username' );
const basePath = context.path;
let showNoticeInitially = false;

Expand Down
Loading

0 comments on commit 2f082a9

Please sign in to comment.