Things work fine when I make a standalone project with two files, one called helperFuncs.js and the other called index.js, where helperfuncs.js has
function stringOfZeros(numZeros) {
//takes in a number and outputs a string with that many zeros;
...
}
module.exports = {
stringOfZeros: stringOfZeros,
}
and index.js has
const helperFuncs = require("./helperFuncs.js");
const stringOfZeros=helperFuncs.stringOfZeros;
let myZeroString = stringOfZeros(17);
console.log(myZeroString);
This works even with no package.json file in the project.
However, if I do the same thing where I create an identical helperFuncs.js file in a small HTML project that has an index.html page and a script.js file on the same level in the directory, and I set the above lines of code from the index.js file into the script.js file where the lines execute inside a window event load listener that otherwise works, I get this error:
TypeError: stringOfZeros is not a function
What am I doing wrong? Does the fact that it's inside a script file somehow require me to use "import" instead of require, or make it mandatory to make a package.json file where otherwise it was optional?
2 Answers 2
Looks like you are trying to run Node JS compatible code in a browser.
Currently browsers do not support this kind of import/export syntax. To use the code above for web applications you need additional special tools that will re-build your code in a way that browser will understand it.
I'd recommend you to try this tools:
1 Comment
Vite that is simpler and faster.Web browsers don't support CommonJS modules or cjs. Instead what you are looking for is ES modules or esm.
It is common for modules on production websites to be bundled into a single javascript file with a bundler. This allows you to use whatever module type you like, and you can apply transformations to your code such as minifying it or adding support for older browsers.
If you like to write your code and run it directly without a bundler. You should use ES modules. You can find lot's of info on this page. But in your case it would look something like this:
helperfuncs.js
export function stringOfZeros(numZeros) {
}
index.js
import {stringOfZeros} from "./helperFuncs.js";
let myZeroString = stringOfZeros(17);
console.log(myZeroString);
You can then load your index.js in your html with the type tag set to module like so:
<script src="index.js" type="module"></script>
module.exportsis not valid. That's for node.js environments.