Skip to content

Instantly share code, notes, and snippets.

@NMinhNguyen
Last active May 21, 2018 22:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save NMinhNguyen/4c3f8fdbd99730df6e00e5c33a23751c to your computer and use it in GitHub Desktop.
transform-object-assign-require for Babel 7
diff --git a/scripts/babel/transform-object-assign-require.js b/scripts/babel/transform-object-assign-require.js
index 2d4d8203b..d98591c16 100644
--- a/scripts/babel/transform-object-assign-require.js
+++ b/scripts/babel/transform-object-assign-require.js
@@ -7,12 +7,16 @@
'use strict';
+const {addDefault} = require('@babel/helper-module-imports');
+
module.exports = function autoImporter(babel) {
function getAssignIdent(path, file, state) {
if (state.id) {
- return state.id;
+ // Based on similar code in @babel/plugin-transform-runtime
+ // https://github.com/babel/babel/blob/a479540/packages/babel-plugin-transform-runtime/src/index.js#L69
+ return babel.types.cloneNode(state.id);
}
- state.id = file.addImport('object-assign', 'default', 'assign');
+ state.id = addDefault(path, 'object-assign', {nameHint: 'assign'});
return state.id;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const {addDefault} = require('@babel/helper-module-imports');
module.exports = function autoImporter(babel) {
function getAssignIdent(path, file, state) {
if (state.id) {
// Based on similar code in @babel/plugin-transform-runtime
// https://github.com/babel/babel/blob/a479540/packages/babel-plugin-transform-runtime/src/index.js#L69
return babel.types.cloneNode(state.id);
}
state.id = addDefault(path, 'object-assign', {nameHint: 'assign'});
return state.id;
}
return {
pre: function() {
// map from module to generated identifier
this.id = null;
},
visitor: {
CallExpression: function(path, file) {
if (path.get('callee').matchesPattern('Object.assign')) {
// generate identifier and require if it hasn't been already
const id = getAssignIdent(path, file, this);
path.node.callee = id;
}
},
MemberExpression: function(path, file) {
if (path.matchesPattern('Object.assign')) {
const id = getAssignIdent(path, file, this);
path.replaceWith(id);
}
},
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment