I'm trying to export a class named Car in JavaScript and import it into another JavaScript file. Both JavaScript files are running live on a console under an html file. (So this may possibly be an html code problem).
I did the export keyword for the file being exported.
I did the import keyword for the file receiving the export.
After this is done, I check my live console running HTML (my Javascript files are linked with the HTML file). And I get a SyntaxError.
//script.js
import { Car } from "./models/car.js";
let car = new Car(123);
console.log( car.id );
//car.js
export class Car {
constructor(id) {
this.id = id;
}
}
And here's an imgur LINK to the html file: https://imgur.com/zK3L6yH
I expect the console in the live html webpage to log out "123".
Instead I got Uncaught SyntaxError: Unexpected token {
I've already tried taking out the curly braces, but then I just get another error.
Related
tried to follow an example from this. To import octokit I first pasted the following lines into my html document as stated by adding the following lines:
<script type="module">
import { Octokit } from "https://cdn.skypack.dev/#octokit/core";
</script>
This just resulted in an Uncaught (in promise) ReferenceError: Octokit is not defined. Moving the line in script tags directly into the script.js file above the code just made one of the main functions appear as undefined (it handled a button click that authenticated a google account and then retrieved data from google sheets via the sheets API).
I then tried all this with new html and js files, adding that code directly to the html had the same result but this time adding it to the start of the js file gives a import declarations may only appear at top level of a module script.js:1
Don't really know what to do from here so any help would be appreciated. Did find this though but it just says the issue is fixed?
I think the best solution is to write your script logic in a separate javascript file, and then import that file in your html at the end of body element.
Here is an example of getting your repositories from GitHub:
repos.js
import { Octokit } from "https://cdn.skypack.dev/octokit";
import { config } from "./config.js";
const GIT_KEY = config.API_KEY;
export const octokit = new Octokit({
auth: GIT_KEY,
});
const repo = await octokit.request(
"GET /users/{username}/repos{?type,sort,direction,per_page,page}",
{
username: "your_username",
}
);
console.log(repo);
repos.html:
<body>
...
<script type="module" src="repos.js"></script>
</body>
I have a typescript file in which there are some functions for validating objects of different classes. So, I have to import those classes into the ts file. For instance,
import { UserDetail } from "../../entity/user/userDetail";
The following block of code depicts a function which is used for validating the objects of the mentioned class.
export function validateSignUpData(userDetail:UserDetail):Array<String>{
let errorMessages = new Array<String>();
/* Some Code */
As you can see the imported class has been used as the function's input type. Now the problem is that it seems we are not allowed to use both import and module.exports simultaneously! Therefore, I am not able to use require in order to get the mentioned function in the Node server file.
When I add the following block of code to my ts file, the following exception is thrown!
module.exports = validateSignUpData;
TypeError: Cannot assign to read only property 'exports' of object '# object'
Question: How can I use all import, modules.export, and export in the same ts file?
I will be glad if someone can help me with the situation.
Thank You
Of course you're able to import that function with require. Just do it like this:
const {validateSignUpData} = require('./my-module.js')
And pay attention to require the compiled javascript file, not the typescript file. They may be in different folders, depending on your build setup.
I want to share a complex typescript exported function to a simple HTML - javascript website
I tried to use npm tsc to transform the file into javascript, but generated files have "exports" functions that creates errors in the browser console.
myFunction.ts
export const getTest = (test: any) => {
// Change test object
return test;
};
generated myFunction.js
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTest = function (test) {
// Change test object
return test;
};
Browser console actually warning me "Uncaught ReferenceError: exports is not defined" when I try to include the file with a script tag in HTML file.
What am I doing wrong?
In order to use the original myFunction.ts file all you need to do is this:
Remove the typing and change the extension to .js:
export const getTest = (test) => {
// Change test object
return test;
};
And then, in your HTML file's <script> tag for that JavaScript file, make sure you set the type attibute to module like so:
<script type="module" src="myFunction.js"></script>
Finally, you'll need to import that functionality where you intend to use it.
That should do it as long as you consider browser compatibility:
ES6 Modules
To make this ultimately clear, here is a Plunkr to demonstrate what I mean.
The export keyword creates a module, which can only be used with a module system (such as webpack).
Either use a module system or drop export to create a normal file that creates global names.
I'm confused about scopes in Javascript and how to get a global function recognized. On my page I have
<script src="base64.js"></script>
defined. Then in another file, I have
var xhr = new XMLHttpRequest;
...
var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
alert(Base64.decode("abc"));
xhr.open("get", full + "myotherfile.js", true);
xhr.send()
The alert executes without a problem. However in the "mytoherfile.js" references to the Base64 class result in a RerefernceError. So at the top of my myotherfile.js I tried
import {Base64} from 'base64';
but this results in a "Uncaught SyntaxError: Unexpected token {" error. What's the right way to include get my global function recognized in a JS file loaded through AJAX?
Edit: The remote loaded JS file is loaded using
this.worker = new Worker(xhrResponseText);
Scripts loaded in the main page are not available in web workers, you have to import them with importScripts not the import command
importScripts("base64.js");
In old-fashioned (non-module) javascript files, global variables are implied to be made on window. So in the first example, Base64.decode("abc") is the same as window.Base64.decode("abc"). In modules, however, this is not true. If you want to access a global variable on the window, it must be done explicitly.
In the module, try changing the reference to Base64 to window.Base64.
Sidenote: If the base64.js file works with a basic script tag import, then it will not work to import it as an es6 module like you have done (import {Base64} from 'base64';). You can read up more on how to import modules here!
Hope that helps!
Update
For clarity, here are a couple examples. Basically, what ever you put in the curly braces ({ Base64}) must be exported from the script being imported, not placed on the window.
<script src=".../base64.js"></script>
<script>
// both are accessible this way because this is NOT a module
// and global variables are assumed to be on the window.
console.log(Base64);
console.log(window.Base64);
</script>
<script type="module">
// Will not work:
// import { Base64 } from ".../base64.js
// import { window.Base64 } from ".../base64.js
// The same as importing view the script tag
// (not needed because the script tag already imported it)
// import ".../base64.js"
// the "global variable" is accessible on the window
console.log(window.Base64)
</script>
The issue is with the path you are referring to. Here are valid paths in type module.
// Supported:
import {foo} from 'https://jakearchibald.com/utils/bar.js';
import {foo} from '/utils/bar.js';
import {foo} from './bar.js';
import {foo} from '../bar.js';
// Not supported:
import {foo} from 'bar.js';
import {foo} from 'utils/bar.js';
Try referring to the path directly. something like this
import {addTextToBody} from '../../someFolder/someOtherfolder/utils.js';
here are valid pathName
Starts with ./ :- same folder
Starts with ../ :- Parent folder
Starts with ../../ :- above parentfolder
I have this function:
// menuAnimate() adds/removes the classes for the mobile menu animation
export default function menuAnimate() {...}
which I am importing into my mocha test file like so:
import { menuAnimate } from '../src/scripts/nav';
However, when I run a test involving menuAnimate, I get an error this error:
/Users/johnsoct/Dropbox/Development/andybeverlyschool/src/scripts/nav.js:67
navToggle.addEventListener('click', menuAnimate);
TypeError: Cannot read property 'addEventListener' of null
This error is being thrown from code further down within nav.js.
navToggle.addEventListener('click', menuAnimate);
How can I export only the function block?
import { menuAnimate } from '../src/scripts/nav';
says "import this file, and let me access one function from it". There's no importing of only part of a file. If you don't want other stuff in that file to run, then you should split the code into two separate files, or rearchitect your code such that it doesn't run when the file loads.
navToggle.addEventListener('click', menuAnimate);
specifically seems like something I'd never expect to execute when the file loads. If you need to bind a listener, you should export a function from your module to do it, then call that function when you actually want the listener to be bound. e.g.
export function initNav() {
var navToggle = ...
navToggle.addEventListener('click', menuAnimate);
}
The top-level scope of a module should have pretty minimal logic of its own. Loading a module on its own isn't something that should have sideeffects like adding an event listener. Pretty much the only time you'd want that is in the initial application JS file.
Also, as mentioned in a comment, since you do
export default ...
you'd want to do
import menuAnimate from
or keep the import you have and do
export function menuAnimate() {...}
without the default.