简体   繁体   中英

Getting an Uncaught reference error - require not defined when I try to import a javascript file

This is my first time actually posting a question here, so please go easy on me. I have been trying to create a really simple app in javascript/html and I have been writing javascript code and testing in jest up until now. Jest has been insisting that I export/import my javascript files with module.exports = {functionName} and const functionName = require('./someAddressHere'); .

This has been working great so far for testing but now I want to hook up my javascript files in an index.js and start configuring my event listeners to the html. When I try the same import method I get a Uncaught ReferenceError: require is not defined . I'm pretty new to web development so is there something I'm missing here or am I going about this all wrong?

Use import and add type="module" in the script tag Ex:

//./data.js

export const data = {
    name: 'mydata'
};

//./main.js

import * as data from './data.js';

alert(JSON.stringify(data));

// html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Import</title>
</head>
<body>
<script type="module" src="main.js"></script>
</body>
</html>

So I ended up using webpack to package all my node modules and distribute to the front.

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