Rosan Paudel
Rosan Paudel

Reputation: 170

how to import constants from another file in node.js

Node.js v16.1.0

I am trying to import constants from another js file in the same directory. But i am not being able to do so.

constants.js

export const API_URL = 'http://localhost:8080';
export const MAX_THREADS = 8;

solution.js

/**
 * Import constants from the constants.js file
 * 
 * Each console.log should log a separate constant
 */

import { MAX_THREADS } from "./constants.js";

Upvotes: 7

Views: 30727

Answers (4)

Dayo Olutayo
Dayo Olutayo

Reputation: 66

If you rename your "solution.js" to solution.mjs, it will work.

The ".mjs" signals to node engine that you are using ES Module System.

Also, putting "type": "module" in packages.json will work as well.

Upvotes: 4

Rashed Rahat
Rashed Rahat

Reputation: 2495

Node.js >= v13

You only need to follow below step be able to use ECMAScript modules.

Add "type": "module" in your package.json.

{
  ...
  "type": "module"
}

Upvotes: 1

Adil Khalil
Adil Khalil

Reputation: 2131

You should do something like the following.

constants.js

const API_URL = 'http://url.com'
const MAX_THREADS = 5

exports.API_URL = API_URL
exports.MAX_THREADS = MAX_THREADS

solution.js

const { API_URL, MAX_THREADS } = require('./constants');

Upvotes: 16

Ron B.
Ron B.

Reputation: 1540

Have you enabled ES modules? Read about it here: https://nodejs.org/api/esm.html#esm_enabling

Upvotes: 0

Related Questions