From e4dad595e14d183180991a0350164261a9a603d3 Mon Sep 17 00:00:00 2001 From: Jean Lauliac Date: Thu, 26 Oct 2017 02:13:37 -0700 Subject: [PATCH] xplat/js: replace import() calls by require.async() calls Reviewed By: mjesun Differential Revision: D6147316 fbshipit-source-id: b93a247ce0830a5db250824d22e81a3b786daf36 --- .../src/JSTransformer/worker/index.js | 16 +++++----- .../src/transforms/DynamicImports.js | 29 +++++++++++++++++++ 2 files changed, 38 insertions(+), 7 deletions(-) create mode 100644 packages/metro-bundler/src/transforms/DynamicImports.js diff --git a/packages/metro-bundler/src/JSTransformer/worker/index.js b/packages/metro-bundler/src/JSTransformer/worker/index.js index 7fbe6512..dc9087bc 100644 --- a/packages/metro-bundler/src/JSTransformer/worker/index.js +++ b/packages/metro-bundler/src/JSTransformer/worker/index.js @@ -33,14 +33,16 @@ export type TransformedCode = { map?: ?MappingsMap, }; +export type Transform = ({| + filename: string, + localPath: string, + options: ExtraOptions & TransformOptions, + plugins?: BabelPlugins, + src: string, +|}) => {ast: ?Ast, code: string, map: ?MappingsMap}; + export type Transformer = { - transform: ({| - filename: string, - localPath: string, - options: ExtraOptions & TransformOptions, - plugins?: BabelPlugins, - src: string, - |}) => {ast: ?Ast, code: string, map: ?MappingsMap}, + transform: Transform, getCacheKey: () => string, }; diff --git a/packages/metro-bundler/src/transforms/DynamicImports.js b/packages/metro-bundler/src/transforms/DynamicImports.js new file mode 100644 index 00000000..0f7eeea0 --- /dev/null +++ b/packages/metro-bundler/src/transforms/DynamicImports.js @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2016-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +'use strict'; + +const template = require('babel-template'); + +const makeAsyncRequire = template('require.async(ARGS)'); + +const plugin = { + inherits: require('babel-plugin-syntax-dynamic-import'), + visitor: { + CallExpression(path) { + if (path.node.callee.type !== 'Import') { + return; + } + const newImport = makeAsyncRequire({ARGS: path.node.arguments}); + path.replaceWith(newImport); + }, + }, +}; + +module.exports = plugin;