Importing Objects from different files in JavaScript Project - javascript

I am complete beginner in JavaScript and web-dev. Most of my programming experience comes from Python and so I am very comfortable with the way python files can be arranged in different folders as modules and can play sort of a plug and play role. So far I am unable to discover that flexibility in JS.
Here is my current project structure:
-root
|-index.html
|-app.js
|-modules
|-test.js
Here is my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Project</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
My app.js:
let hello = Hello()
Finally my modules/test.js:
class Hello(){
constructor(){
console.log('Hello World');
}
}
When I run it I get the error message: Uncaught ReferenceError: Hello is not defined at app.js:1:1
What do I do to achieve my desired results? Regards.

Have you tried:
modules/test.js:
export class Hello(){
constructor(){
console.log('Hello World');
}
}
app.js:
import { Hello } from './modules'
let hello = new Hello()
Or, if you use the expor default, do not need the curly braces, as you do not need to secify what you are exporting. Like so:
modules/test.js:
export default class Hello(){
constructor(){
console.log('Hello World');
}
}
app.js:
import Hello from './modules'
let hello = new Hello()

First of all, in your index.html, when you are working with modules, you should add the type of the script
<script type="module"></script>
In the modules, after you do some code and logic, you export your class with the export declaration at the end, like so:
export default Hello;
in your app.js, when you want to use some module, you import it like so:
import Hello from "./modules/test.js";
And then you would be able to use the imported data. You can use as many imports as you want.
Here is a working example with the minor tweaks on your code:
CodeSanbox demo

So both the answers provided by rustyBucketBay and Yavor are correct but incomplete. The working solution is doing what each of the two suggested but together. Here is what eventually works:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Project</title>
</head>
<body>
<script type="module" src="app.js"></script>
</body>
</html>
modules/test.js:
export default class Hello{
constructor(){
console.log('Hello World');
}
}
app.js:
import Hello from 'modules/test.js'
let hello = new Hello()

You need to export the function from test.js and import it in app.js

Related

How to use NPM modules in plane javascript and html project?

I want to use axios in my simple project but it doesn't work but when I use CDN for axios it works..!!
HERE'S THE MY CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module" src="./app.js"></script>
</body>
</html>
APP.JS
import { axios } from ("axios");
const getData = async () => {
const data = await axios.get("https://swquotes.herokuapp.com/random");
console.log(data);
};
window.onload = getData();
I want to know ho can i use npm packages directly in my project without react
If you have access to node_modules then you can import it directly from the folder, even though thats dirty and is not recommended.
<script src="node_modules/<your_package>/dist/<entry_file>"></script>
Your problem is a little different, just to narrow it a little down - the browser doesnt understand your import statement as it has to be transpiled with webpack.
import { axios } from ("axios");
So unless you import directly from CDN or use our dirty shown way of importing it - it wont and should not work

Why a module is shown connected but still not working? [duplicate]

This question already has answers here:
What does a script-Tag with src AND content mean?
(4 answers)
Closed 1 year ago.
Whenever I connect a JS module, in DevTools' "Sources", the module is shown as connected.
However, the function that I try to run out of it, simply doesn't work.
What can be done to run the function from the module?
function consoleLog () {
console.log('The module is working')
}
export default consoleLog;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="module" src="./module.js">
import consoleLog from './module';
consoleLog();
</script>
</head>
<body>
</body>
</html>
Your problem is that you have code and an src attribute on your script tag, script tags should have one or the other. You also don't have to create a script tag for your module if you import it in another module, like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="module">
import consoleLog from './module.js';
consoleLog();
</script>
</head>
<body>
</body>
</html>

Import Vue breaks Vue

Can someone explain the WHY of how Import Vue from 'vue' breaks the rendering of the template? I've seen other answers on how to work around this, but none of them have gone into the details of why it breaks.
I ran npm init and npm install vue, not using the CLI.
I created an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<script type="text/javascript" src="node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<first-task></first-task>
{{msg}}
</div>
<script src="app.js"></script>
</body>
</html>
and an app.js looking like:
import Vue from 'vue/dist/vue.js'; //Remove to fix
Vue.component('first-task', {
template: '<p>Hello World!</p>'
});
var app = new Vue({
el: '#app',
data: {
msg: "Hello World"
}
});
Removing the import, it renders fine, but it's unclear to me why this happens. My only guesses are that the default new Vue doesn't reference the full build, or that the implicit Render() doesn't get called, but I'm unsure of how to look into this more.
import statements may only appear in a javascript module
<script type="module" src="app.js"></script>
Should fix it, though you would not need to import Vue with your current code anyway, as you have seen

while using npm start in the terminal of visual studio I get an error

I am using JavaScipt ES6 with Node. I am using visual studio code. I am getting this error when I run npm start:
The error is:
× C:\Users\markp\source\repos\bioinvisionTest\index.html:1:31: Imports and requires are not supported inside inline <script> tags yet
in other programs the import works. This one it doesn't. All that is in the program is this:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="demo"></div>
<script>
import TestComponent from "./components/Testcomponent"
</script>
</body>
</html>
and in the components folder there is file called Testcomponent js that contains this:
function TestComponent() {
console.log("test component js")
}
export default {
TestComponent
}
return key is somting which you can't simply ignore if it's multiline codes.
If you are uinsg Creaet-react-app as generator then i will recommend use APP.js as base and inject your component in that file for now. Later you can redesign .
If you are using only HTML and JS file then you should import react and react-dom library in your index.html file .
One page React App , place in your html file.
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Greeting extends React.Component {
render() {
return (<p>Hello world</p>);
}
}
ReactDOM.render(
<Greeting />,
document.getElementById('root')
);
</script>
Modules are natively suppported
refer MDN docs
Try adding type="module" to your script tag.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="demo"></div>
<script type="module">
import TestComponent from "./components/Testcomponent"
</script>
</body>
</html>

I have exported some variables from a page and tried to import the variables. But it is not working

I have exported some variables from a page and tried to import the variables. But it is not working. I researched this issue but not found any solutions. I am using Mac Chrome Version 76.0.3809.100. Any help would be appreciated.
export.js(http://localhost:8888/javascript/es6/export.js)
"use strict";
export const foo = "bar";
export const bar = "foo";
import.js(http://localhost:8888/javascript/es6/import.js)
"use strict";
import { foo } from "export.js"
console.log(foo);
Result
import.html(http://localhost:8888/javascript/es6/import.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="import.js"></script>
</body>
</html>
You cannot use the import syntax on normal <script> tags you need to add the <script type="module"> attribute to it to enable importing:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="import.js" type="module"></script>
</body>
</html>
From MDN script docs and MDN guide on modules here:
type This attribute indicates the type of script represented. The
value of this attribute will be in one of the following categories:
module: Causes the code to be treated as a JavaScript module. The
processing of the script contents is not affected by the charset and
defer attributes.

Categories