Update the js file by incorporating the import statement

Currently, I am in the process of transitioning to using imports instead of requires for modules. Here is an example of my previous code:

const { NETWORK } = require(`${basePath}/constants/network.js`);

The content of network.js file is as follows:

export const NETWORK = {
  eth: "eth",
  sol: "sol",
};

module.exports = {
  NETWORK,
};

When attempting to import, I have tried various syntaxes such as:

import { NETWORK } from '../constants/network.js';
import NETWORK  from '../constants/network.js';
import * as NETWORK  from '../constants/network.js';

However, I encounter an error that states:

This file is being treated as an ES module because it has a '.js' file extension and '..\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///../constants/network.js:6:1
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:526:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

Even when renaming the file to 'network.cjs', I face another error:

SyntaxError: Unexpected token 'export'

I am seeking guidance on how to appropriately import variables from js files using the import statement.

Answer №1

To successfully export items in commonjs from your network.js file, you should eliminate the unnecessary "module.exports" section. This step is crucial as it follows the correct practice outlined in this guide on exporting in commonjs. Once you remove the unnecessary part, your initial import line will function properly:

import { NETWORK } from '../constants/network.js';
Therefore, any additional import lines can be removed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring Data in Vue.js Components through Props

I've encountered an issue while trying to pass a prop from the main Vue instance to a component. While one of the props is being successfully passed, the second one seems to be causing some trouble. Main Instance var app7 = new Vue({ el: &apos ...

Ways to make a personalized item within an array using javascript

JSON: (The array within this.schedulerForm.get("schedularList").value contains the following array: const result = [{ formula_id:1, quantity1:10, quantity2:20, quantit ...

The type definition file for '@wdio/globals/types' is nowhere to be found

I'm currently utilizing the webdriverio mocha framework with typescript. @wdio/cli": "^7.25.0" NodeJs v16.13.2 NPM V8.1.2 Encountering the following error in tsconfig.json JSON schema for the TypeScript compiler's configuration fi ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

Display and conceal various elements in Vue.js using a data list

I'm a beginner in Vue.js, currently using Vue+Webpack. I am trying to make each link display data based on their respective ids when clicked, and match with the show attribute. I have created this functionality in a .vue file. export default { el ...

searchkit - Issue with Maintaining State of RefinementListFilter Checkboxes

I was curious about the functionality of the RefinementListFilter in searchkit. I have multiple filters that are boolean values, such as {field: 'hasChildren': {'1' : 'Yes', '0': 'No'}} to illustrate the tr ...

Using TypeScript to specify a limited set of required fields

Can a custom type constraint be created to ensure that a type includes certain non-optional keys from an object, but not all keys? For instance: class Bar { key1: number key2: Object key3: <another type> } const Y = { key1: 'foo' ...

Next.js has a problem where it displays incorrect data when users navigate rapidly between pages

An unusual challenge has emerged while rendering data on a Next.js page in my application. Here's the scenario: I've created a Next.js page that showcases customer details based on a query parameter called cid. The page retrieves customer data an ...

Creating a dependent picklist feature using node.js and express

I am currently delving into the world of node.js and express. In my node.js application, I am utilizing express along with express-handlebars as the templating framework. My goal is to incorporate a dependent picklist that dynamically renders based on the ...

'Unable to locate the identifier "system" in Angular 2' - troubleshoot this unique error

My routes file contains a reference to 'system' which is causing an error in my Visual Studio Code. The error states that it cannot find the name 'system'. I have attached a screenshot for reference: https://i.sstatic.net/W2oD2.png ...

Tips for retrieving the output from an Azure Function

Just getting started with Azure Functions and I have this code snippet: module.exports = function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); context.log(context.req.body.videoId) ...

In what way can I indicate parsing "per dataset" using Chart.js?

I'm currently exploring the usage of the yAxisKey option in ChartJS while defining a dataset. However, I'm encountering difficulties in replicating this specific example from the documentation. Despite my efforts to search for issues related to y ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

Sequelize: Query results do not have defined instance methods and properties

The Sequelize version is 6.6.2 Mysql2 version: 2.2.5 I have constructed my Model in the following manner and defined methods as shown: interface IUserAttributes { user_id: number; logon_name: string; user_password: string; full_name: string; di ...

Navigating the landscape of asynchronous asset loading can present challenges. Attempting to access assets immediately may result in receiving

I have encountered an issue while trying to load my assets into an array using a function called LoadJSON(). This function utilizes THREE.ObjectLoader() to load JSON files. The problem arises when I attempt to access the members of the array immediately af ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...

Invoking a function containing an await statement does not pause the execution flow until the corresponding promise is fulfilled

Imagine a situation like this: function process1(): Promise<string> { return new Promise((resolve, reject) => { // do something const response = true; setTimeout(() => { if (response) { resolve("success"); ...

Is it possible to handle both ajax form submissions and browser post submissions in express.js?

On my website, I have implemented a contact form using express.js (4.0). I am contemplating how to manage the scenario where a user disables JavaScript. If the last part of my routing function looks like this: res.render('contact.jade', { tit ...

Enhancing Google Custom Search Engine with Bootstrap3 and CSS3 styling

I'm looking for guidance on how to customize the appearance of a Google Custom Searchbar on my website. Is it feasible to style it using CSS3 and Bootstrap 3 like the example in the image below? Any assistance is greatly appreciated. ...

Extracting Data from JSON Using Vue.js

I am facing an issue with extracting data from a JSON file using Vue.js. Below is the HTML and JSON data along with the script. Any help would be appreciated. <!DOCTYPE html> <html> <head> <title>Vu ...