How to load specified export using SystemJS

If I have lib, say utils.js , which looks like

 exports.foo = function () { return 'foo'; }; exports.bar = function () { return 'bar'; }; 

What can be used as follows

 import {foo} from './libs/utils'; console.log(foo()); 

Not very impressive, but I feel that this problem is causing the problem described in this publication. In any case, I cannot get this to work in conjunction with SystemJS . I need to change the code to fix it.

 import utils from './libs/utils'; console.log(utils.foo()); 

Here is my systemjs-config file:

 SystemJS.config({ map: { 'plugin-babel': 'node_modules/systemjs-plugin-babel/plugin-babel.js', 'systemjs-babel-build': 'node_modules/systemjs-plugin-babel/systemjs-babel-browser.js', }, packages: { '.': { defaultJSExtensions: 'js' } }, transpiler: 'plugin-babel' }); 

Thus, only an exports object can be loaded, not a named export. Could this be fixed somehow?

UPDATE I get the impression that it can be fixed using formats

  meta: { './libs/utils.js': { format: 'cjs' } } 

But for now it gives the same problems

+3
source share
1 answer

This is not specific to SystemJS. SystemJS behaves the same as version 0.20 because it is that standardization of the ES6 module is standardized.

When, as in your question, you import CommonJS modules (exported via module.exports ) using ES6 import , you will get only the whole export and you will not be able to immediately destroy the exported names.

However, when you import modules that are exported through ES6 export , you can destroy the exported names.

So, all this is by design. Guy Bedford wrote about this on his blog and referred to module standardization, which continues for NodeJS:

... named exports will no longer be allowed when importing the CommonJS module from the ES module and is discussed at https://github.com/nodejs/CTC/pull/60/files#diff-2b572743d67d8a47685ae4bcb9bec651R217 .

That is, import { name } from 'cjs.js' , where cjs.js is a CommonJS module will no longer be supported, and instead import cjs from 'cjs.js'; cjs.name import cjs from 'cjs.js'; cjs.name .

Workaround for interacting with __esModule :

We will continue to support the __esModule flag in interop, though, allowing us to cancel the named export for these cases.

So, if the cjs.js module was written:

 exports.__esModule = true; exports.name = function () { ... } 

then one could have import { name } from 'cjs.js'; , even though cjs.js is a CommonJS module, although this __esModule will ultimately also be obsolete in the long run.

+3
source

Source: https://habr.com/ru/post/1264381/


All Articles