Home > Back-end >  Export a just-imported modified variable in javascript
Export a just-imported modified variable in javascript

Time:10-27

How to export a just-imported variable which I modify along the javascript file? My attempt is below:

import { foo } from "bar"

foo = 2

export foo;

I try the code above, but I receive the log as follows:

SyntaxError: Unexpected token 'export'

CodePudding user response:

You need to name the export:

import { foo } from "bar"

foo = 2

export { foo } // short for `export { foo as foo }`

However, that still won't get you far, since imported variables are not writable. foo = 2 doesn't work, you're not allowed to modify the import. You might as well drop that and just write

const foo = 2;
export { foo as foo }

or

export const foo = 2;

for short.

CodePudding user response:

You cannot change the imported variable this way. Only the module that exported the variable can change its value.


"you should use default export" - no, why should you?

After Bergi's comment, I realized that I caused a misunderstanding because I left some points missing and I clarified a little.

// bar.js

const bar = ...

export { bar }

Re-export:

// foo.js   

export * from "./foo"; // doesn’t re-export default
// or
export * as myFoo from "./foo"; // re-export with default
// or
export { foo } from "./foo";
// or
export { foo as myFoo } from "./foo";
// ...

Or you can export without asterisks or curly brackets. (Before I edited, I wrote you should use default export in this line. This is where Bergi stepped in)

import { foo } from "bar"
export default foo;

If you read the documentation, you'll also see the different features of importing and exporting.


I will follow your comments

I want to define it in a file

// define.js

import express from "express";

const router = express.Router();

export { router };

modify it on another

// modify.js

import { router } from "./define.js";

router.get("/", (req, res) => {
  res.send({ message: "Hello world" });
});

export { router };

export to my app in some other file

// app.js

import express from "express";
import { router } from "./modify.js";

const app = express();

app.use("/", router);

app.listen(3000, () => {
  console.log("server listening");
});

Let's make a request via browser or terminal. I will prefer terminal here.

curl -X GET http://localhost:3000/
// {"message":"Hello world"}  

We could do imports and exports differently (like export default, etc.). If you look at the documentation for this, you can do it with different variations.

  • Related