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>
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.