[英]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.这是我第一次在这里实际发布问题,所以请 go 对我放心。 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.
我一直在尝试在 javascript/html 中创建一个非常简单的应用程序,直到现在我一直在编写 javascript 代码并进行测试。 Jest has been insisting that I export/import my javascript files with
module.exports = {functionName}
and const functionName = require('./someAddressHere');
开玩笑一直坚持我导出/导入我的 javascript 文件
module.exports = {functionName}
和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.到目前为止,这对于测试来说效果很好,但现在我想在 index.js 中连接我的 javascript 文件,并开始将我的事件侦听器配置到 html。 When I try the same import method I get a
Uncaught ReferenceError: require is not defined
.当我尝试相同的导入方法时,我得到一个
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?我对 web 开发还很陌生,所以这里有什么我遗漏的东西还是我要解决这一切都错了?
Use import and add type="module"
in the script tag Ex:使用import并在脚本标签中添加
type="module"
例如:
//./data.js //./data.js
export const data = {
name: 'mydata'
};
//./main.js //./main.js
import * as data from './data.js';
alert(JSON.stringify(data));
// html // 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.所以我最终使用 webpack 到 package 我所有的节点模块并分发到前面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.