Skip to content

Instantly share code, notes, and snippets.

@LearningNerd
Last active July 10, 2024 10:43
Show Gist options
  • Save LearningNerd/08a5039a7c5cddf7342ecd0a32da94e3 to your computer and use it in GitHub Desktop.
Save LearningNerd/08a5039a7c5cddf7342ecd0a32da94e3 to your computer and use it in GitHub Desktop.
Using import/export for front-end modules, example 1
export function helper(x) {
console.log(x);
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ..... other <head> stuff here .... -->
<!-- *** IMPORTANT: use type="module" here! *** -->
<script type="module" src="main.js"></script>
</head>
<body>
<!-- ... <body> stuff here ... -->
</body>
</html>
// IMPORTANT:
// - Must preface relative file paths with / or ./ etc
// - Must include the .js at end of the file name
// - Must surround named imports with { }
import {helper} from "./helper.js";
helper("This works!");
@Wils0nDev
Copy link

Wils0nDev commented Apr 5, 2021

hi, when i do that i get a CORS error. you know why ?

index.html
main.js
transaccion.js

main.js
import { Transaccion } from "./transaccion.js"

Access to script at 'file:///C:/nodejs/gestor-de-gastos/frontend/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

@LearningNerd
Copy link
Author

Hey @wStrike18! I believe you need to run a local web server to test your code if you're using modules -- see this article from MDN: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server

@harivonyR
Copy link

In javascript front-end, module imported must end with .js in path. Overwise it will not work

@a-creamy
Copy link

Thanks for the example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment