简体   繁体   中英

Can two javascript files communicate through referencing in html body?

I am trying to export from functions.js and import it to login.js, but when i load localhost:3000 i get error "Uncaught SyntaxError: Cannot use import statement outside a module" and "Uncaught SyntaxError: Unexpected token 'export'"

Is webpack only solution for this? I am in late stage of my project and trying to find easy work around.

Code:

<html>
 <body
    <script src="/js/exports/functions.js"></script>
    <script src="/js/login.js"></script>
  </body>
</html>

Since you're asking for an easy workaround , you may consider using globals .

All your JavaScript files have a common global scope. The common global object context between your script files for a browser is window . When you assign a variable like x = 1 , it gets assigned to window.x . If you define a function like function go() {} it gets assigned to window.go . If you try to read a variable like foo , it's actually looking for window.foo . All your JavaScript files will have access to this window object and its properties, both explicitly with window.foo and implicitly with just foo .

Also worth mentioning that JavaScript modules are a thing. But if you're just looking for a quick solution and have no time to learn something new right now, then a carefully used global can get you out of a pinch.

If you're importing manually with <script> then you shouldn't have to use import , you can straight use the library that is provided to you.

index.html

<html>
  <head>
    <!-- Order matters! -->
    <!-- Sum has to be imported first so `print.js` can use it -->
    <script src="./sum.js"></script>
    <script src="./print.js"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

sum.js

const sum = (a, b) => {
    return a + b
}

print.js

var result = sum(1, 1) // Notice how you dont have to import any library, it's on the global namespace
console.log("1 + 1 = ", result)

Webpack 's job is to bundle all the JS files together into one file. So if you wanna use import then webpack will be the way you want to choose sure.

But understand what the purpose of each tool is and why it was created. Webpack was not created so you can use import , and you can still make projects without Webpack. But it will help you for sure in some cases and no knowledge goes wasted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM