Skip to main content

@babel/plugin-proposal-filtered-namespaces

Transforms filtered namespace imports and re-exports (import { a, b } as ns from "mod"), and the exports option of dynamic import().

Filtered namespaces are part of the Deferred Re-exports proposal. They let you import a namespace object that only exposes some of the exports of a module.

info

This plugin only compiles filtered namespaces. To parse export defer declarations, you need to enable the deferredReexports parser plugin. Babel does not support transpiling export defer.

Example​

Static imports and re-exports​

input.js
import { a, b } as ns from "mod";

ns.a;

will be transformed to

output.js
const ns = Object.freeze(Object.defineProperty({
__proto__: null,
get a() {
return _a;
},
get b() {
return _b;
}
}, Symbol.toStringTag, {
value: "Module"
}));
import { a as _a, b as _b } from "mod";
ns.a;

Re-exports are compiled in the same way:

input.js
export { a, b } as ns from "mod";
output.js
const _ns = Object.freeze(Object.defineProperty({
__proto__: null,
get a() {
return _a;
},
get b() {
return _b;
}
}, Symbol.toStringTag, {
value: "Module"
}));
import { a as _a, b as _b } from "mod";
export { _ns as ns };

The generated code still uses ES modules, so it can be combined with any of Babel's modules transforms, such as @babel/plugin-transform-modules-commonjs.

Dynamic imports​

input.js
import("mod", { exports: ["b", "a"] });

will be transformed to

output.js
var _exports;
import("mod", {
exports: _exports = ["a", "b"]
}).then(babelHelpers.createModuleNsFilter(_exports));

Installation​

npm install --save-dev @babel/plugin-proposal-filtered-namespaces

Usage​

babel.config.json
{
"plugins": ["@babel/plugin-proposal-filtered-namespaces"]
}

Via CLI​

Shell
babel --plugins @babel/plugin-proposal-filtered-namespaces script.js

Via Node API​

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-filtered-namespaces"],
});

Caveats​

Babel does not support transforming filtered namespaces that are combined with import defer or export defer yet, such as import defer { a } as ns from "mod" or export defer { a } as ns from "mod".

References​