Home > Net >  Node.js - combine default export with non default exports
Node.js - combine default export with non default exports

Time:12-03

How do you translate this code:

import a from "./a"

export default a;
export { default as b } from "./b";

To node.js using classic syntax?

// This is what I have tried
module.exports = {
   ...require("./a"),
   b: require("./b),
}

import a, { b } from "index";

const a, { b } = require("index");

CodePudding user response:

This is just:

module.exports = require("./a");
module.exports.b = require("./b);

Be careful that the order of the exports is important: default comes first.

Or, if you prefer:

module.exports = Object.assign(require("./a"), {
    b: require("./b")
});

CodePudding user response:

To use with require you'll need a bit more. If you can use import/export it'll be better.

If you compile this code with TypeScript, this is the generated output

/index.ts

Input

import a from "./a";

export default a;
export { default as b } from "./b";

Output

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
exports.__esModule = true;
exports.b = void 0;
var a_1 = require("./a");
console.log("a", a_1["default"]);
exports["default"] = a_1["default"];
var b_1 = require("./b");
__createBinding(exports, b_1, "default", "b");

/test.ts

Input

import a, { b } from ".";

console.log("a", a);
console.log("b", b);

Output

"use strict";
exports.__esModule = true;
var _1 = require(".");
console.log("a", _1["default"]);
console.log("b", _1.b);

CodePudding user response:

You can use default and non-default like this :

    export default function  A(){}
    export function B(){}
    export function C(){}
´´´

To import use :


import A, {B,C} from "...path from component";
... your code

´´´

Hope help you ;)

  • Related