james wisley
james wisley

Reputation: 119

How to import in nodejs

Every time I try to import into my nodejs file I get the error, cannot import outside a module

I have tried multiple solutions on StackOverFlow such as adding

"type":"module"

and setting file extensions to .mjs

I want to import constants from a different file but I am not sure how to

example

Constants.js


export const help1 = 5
export const help2 = 6
export const help3 = 7

backend.js

import {help1,help2,help3} from './constants.js'

How should I import them?

Upvotes: 1

Views: 60

Answers (1)

A D
A D

Reputation: 466

You can use the below code. Object.freeze will not allow any change in object properties.

Constants.js

module.exports = Object.freeze({
    HELP1: 5,
    HELP2: 6,
    HELP3: 7
});

backend.js

var constants = require('./constants');

console.log(constants.HELP1); // 5

Upvotes: 2

Related Questions