Unable to include a JavaScript file within another JavaScript file

Currently, I am working on a project where I am utilizing Django for the backend and HTML/CSS/JS for the frontend development.

On a specific HTML page, I am including two JS files: dom_creator.js and console_page.js. My goal is to access the functionalities of dom_creator within console_page, but no matter what approach I take, I am unable to locate the correct import statement. Additionally, some of the ES6 import statements I have tried actually cause console_page.js to malfunction.

Another component in my HTML is the imported module console_module.js. In this file, I have successfully imported dom_creator.js using the following syntax:

import {function1, function2} from "./dom_creator.js"

My question is, how can I import functions from dom_creator into console_page.js, which is not a module? Despite consulting various solutions on Stack Overflow, none of them have proven effective in my case.

Answer №1

If you're encountering issues with importing JavaScript files in your HTML code, the solution may lie in adjusting the script element.

Ensure you add the attribute TYPE = "MODULE" to the script element like so:

Here's an example of how to structure your HTML code:

<script type="module" src="./myscript.js"> </script>

And here's how your JavaScript file may look:

function print(y){

    console.log(y);

}

export {print};

To successfully import the print function into another JavaScript file, follow these steps:

import {print} from "./main.js" // make sure to include .js extension

print('hello world');

// Alternatively, import all functions at once

import * as main from "./main.js" // make sure to include .js extension

// To use the latter method:

let variable = main.print('hello world');

Answer №2

To import a function into another file, you must first export it.

If you are using es5 (commonly used in NodeJs), you can export it as shown below:

var myfunction = function () {}

module.exports = { myfunction }

In newer versions (es6+), you can use export like this:

var myfunction = function () {}

export myfunction;
// Then you can import it like: import {myfuntion} from 'file.js';
// Or with another name: import {myfuntion as john} from 'file.js';

// Or export it as default like:
export default myfunction;
// Then you can import it like: import myfuntion from 'file.js';
// Or with any other custom name: import john from 'file.js';

The only thing I couldn't quite grasp from your question is the connection to Django 🤔

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

Handling mousewheel events for child elements and their parent element

I developed a custom jQuery plugin that replaces the default scrollbar with my own, managing mousewheel and bar dragging events. The issue arises when I place content containing my custom scrollbar within another content also using my scrollbar. When I sc ...

Encountered a React error stating: `TypeError: this.state.projects.map is not a

export default class Timeline extends Component{ state = { projects : [], }; async componentDidMount(){ const response = await api.get("/projects"); this.setState({projects: response.data}); } render(){ return ( <div className ...

Issues have been identified with the capabilities of Vue's Mutations and Actions

My Index.js from the Store Folder import Vue from "vue"; import Vuex from "vuex"; import state from "../store/state"; import mutations from "../store/mutations"; import actions from "../store/actions"; Vu ...

Is there a way to modify the appearance of blocks in Scratch/Blockly?

I am currently working on customizing the appearance of the blocks in Scratch by looking into adjusting the GitHub repository of scratch-blocks (https://github.com/LLK/scratch-blocks). There is a chance that I might need to modify the GitHub repository of ...

Working towards ensuring my website is responsive

Hello, I am a CSS beginner currently working as an intern. My task is to make a website's CSS compatible with Internet Explorer, and then make it responsive and scalable. Essentially, the design should retain its appearance when the window size change ...

What is the best way to showcase the chosen items in a dropdown menu?

There seems to be an issue with the selected item not appearing in the input field. export default function BasicSelect() { const [sortBy, setSortBy] = useState(""); const [condition, setCondition] = useState(""); const [delivery, ...

Is there a way to make a React Component to update and navigate to a specific position using react-sound

Currently, I am in the process of constructing an audio player utilizing react-sound. One feature I aim to incorporate is the ability to return to a specific position within the audio track. At the moment, this is my approach: goToVeryCustomPosition() { ...

Incorporating React.js into HTML DOM Elements

As a beginner in react js, I'm facing an issue regarding DOM elements. Within my component, there is a table. When hovering over a cell, I want to highlight both the corresponding row and cell. Additionally, I need to obtain the coordinates of the hov ...

Strategies for effectively managing numerous API requests

My current setup involves fetching about five API calls simultaneously. While it works at times, most of the time it results in a fetch error. Is there a way to prevent these errors from occurring when running the API calls? app.post("/movie/:movieN ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

Tips for dynamically appending a string to a predefined variable in React

When I was working on creating a text input space using the input type area and utilizing the onChange utility, everything was running smoothly. Now, my task is to incorporate an emoji bar and insert a specific emoji into the input space upon clicking it. ...

What are the steps to store my information in MongoDB with the help of Expressjs?

As a backend developer beginner, I am currently working with an array called Movie using expressJS. My goal is to save this array in a MongoDB database, specifically using Mongodb Atlas. Any help or guidance on this process would be greatly appreciated. I ...

importing files from Uploadcare using ngCordova MediaFile

I am facing an issue while attempting to upload a sound file from ngCordova's $cordovaCapture service to UploadCare. The `uploadcare.fileFrom('object')` function is failing with an 'upload' error even though I have set the public k ...

React form input values fail to refresh upon submission

After attempting to upload the form using React, I noticed that the states are not updating properly. They seem to update momentarily before reverting back to their original values. I am unsure of why this is happening. Take a look at this gif demonstrati ...

Unexpected behavior: custom event firing multiple times despite being emitted only once

I am utilizing the ws module for incorporating web sockets functionality. An event named newmessage seems to be triggering multiple times in correlation with the number of active sockets connected to the web-socket-server. The scenario puzzled me initiall ...

Guide on transferring JSON information from a client to a node.js server

Below is the code snippet from server.js var express = require("express"), http = require("http"), mongoose = require( "mongoose" ), app = express(); app.use(express.static(__dirname + "/client")); app.use(express.urlencoded()); mongoose.con ...

Unable to retrieve JSON data in servlet

I am having trouble passing variables through JSON from JSP to a servlet using an ajax call. Despite my efforts, I am receiving null values on the servlet side. Can someone please assist me in identifying where I may have gone wrong or what I might have ov ...

Using JavaScript AJAX to send a PHP POST request

I am encountering an issue where my data is not being inserted into the database. When I check the console log and network, I receive a blank response. The problem might stem from the fact that my JavaScript source code contains a mix of other stack overfl ...

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...

Executing a php function upon onchange event triggered by CKEditor

My task involves invoking a PHP function when I suspect it is being triggered by an ajax call. Utilizing ckeditor, I aim to detect any keyboard activity and believe that using onchange will serve this purpose. Subsequently, I plan to execute a function t ...