n-riesco / jp-babel

jp-babel is a babel kernel for the Jupyter notebook
Other
86 stars 16 forks source link

`import` statements scoped to cell #11

Open gnestor opened 7 years ago

gnestor commented 7 years ago

If imported modules are referenced outside of the cells where they're imported, they're undefined:


// In[1]
import infer from 'json-schema-generator';

// In[2]
infer

// ReferenceError: infer is not defined
//     at evalmachine.<anonymous>:3:1
//     at ContextifyScript.Script.runInThisContext (vm.js:25:33)
//     at Object.exports.runInThisContext (vm.js:77:17)
//     at run ([eval]:608:19)
//     at onRunRequest ([eval]:379:22)
//     at onMessage ([eval]:347:17)
//     at emitTwo (events.js:106:13)
//     at process.emit (events.js:191:7)
//     at process.nextTick (internal/child_process.js:744:12)
//     at _combinedTickCallback (internal/process/next_tick.js:67:7)
n-riesco commented 7 years ago

This is the result of how babel transpiles import statements. E.g.:

var uuid = require('uuid');
uuid.v4();

import v4 from 'uuid';
v4();

transpiles into:

'use strict';

var _uuid = require('uuid');

var _uuid2 = _interopRequireDefault(_uuid);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var uuid = require('uuid');
uuid.v4();

(0, _uuid2.default)();

I don't know how easy it'd be to override these transpilation rules.

gnestor commented 7 years ago

@n-riesco I don't really understand the difference here between compiled require and compiled import... import doesn't involve a _interopRequireDefault?

n-riesco commented 7 years ago

@gnestor More on this issue: if understand correctly, babel transpiles import statements like this to allow a new magic feature in ES6 called import binding (see an interesting discussion about import binding here).

The immediate consequence (to jp-babel) is that execution cells must include all the import statements used by the code in the execution cell.

Announcement commented 6 years ago

the biggest difference is the __default property being utilized. @gnestor