Skip to content
This repository has been archived by the owner on Oct 17, 2020. It is now read-only.

Commit

Permalink
Make sure only the first define() is namespaced
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan-zaera authored and jbalsas committed Jul 10, 2017
1 parent e6700ca commit 6550dc4
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,13 @@ exports[`does not namespace already qualified define calls 1`] = `
"
Other.Namespace.define([], function () {});"
`;

exports[`only namespaces the first appearance of define() in the source 1`] = `
"
if (window.define) {
Liferay.Loader.define([], function () {
console.log(define('this should not be namespaced'));
});
}
Liferay.Loader.define('this should not be namespaced');"
`;
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,27 @@ it('does not namespace already qualified define calls', () => {

expect(code).toMatchSnapshot();
});

// It is not clear what would be the best way to handle multiple define calls in
// the code.
// On the one hand, it is faster to only change the first appearance as 99% of
// the time we will be processing AMD modules with define calls issued by us.
// On the other hand, some third party modules (like jQuery, for instance) issue
// define() calls inside their code. We expect only one such call, but if
// someone does anything more exotic than that, this plugin could "fail".
it('only namespaces the first appearance of define() in the source', () => {
const source = `
if(window.define) {
define([], function() {
console.log(define('this should not be namespaced'));
});
}
define('this should not be namespaced')
`;

const { code } = babel.transform(source, {
plugins: [plugin],
});

expect(code).toMatchSnapshot();
});
7 changes: 6 additions & 1 deletion packages/babel-plugin-namespace-amd-define/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
*/
export default function({ types: t }) {
const namespaceVisitor = {
ExpressionStatement(path) {
ExpressionStatement(path, state) {
if (state.namespaced) {
path.stop();
}

const node = path.node;
const expression = node.expression;

Expand All @@ -17,6 +21,7 @@ export default function({ types: t }) {

callee.name = `${namespace}.define`;

state.namespaced = true;
path.stop();
}
}
Expand Down

0 comments on commit 6550dc4

Please sign in to comment.