最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReferenceError: require is not defined in ES module scope, you can use import instead - Stack Overflow

programmeradmin4浏览0评论

Here I have mentioned the Files I have used. I have tried in both ways, by adding and removing of "type" : "module" tag in package.json file.

App.js

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('app.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

import { hello } from './sell.js';
hello();


app.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>React JS </title>
</head>
<body>
<h1>JavaScript Tutorial</h1>

<script type="module" src="app.js"></script>
</body>
</html>

sell.js

export let hello = () => {
    console.log("heyy shreya suman");
}

Here I have mentioned the Files I have used. I have tried in both ways, by adding and removing of "type" : "module" tag in package.json file.

App.js

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('app.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

import { hello } from './sell.js';
hello();


app.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>React JS </title>
</head>
<body>
<h1>JavaScript Tutorial</h1>

<script type="module" src="app.js"></script>
</body>
</html>

sell.js

export let hello = () => {
    console.log("heyy shreya suman");
}
Share Improve this question asked Apr 23, 2022 at 17:08 shreya sumanshreya suman 711 gold badge3 silver badges5 bronze badges 2
  • 1 why are you using both ESM syntax and monjs? change import {hello} from './sell.js' to const {hello} = require('./sell.js') – about14sheep Commented Apr 23, 2022 at 17:13
  • 1 It seems you are missing that the javascript running on the server and the javascript running in each browser page are two totally separate programs. You cannot mix them - you need to make them municate. – Bergi Commented Apr 23, 2022 at 20:34
Add a ment  | 

1 Answer 1

Reset to default 8

Look, there are 2 ways to import somthing

  1. var http = require('http');
  2. import http from "http"

But you cant use import and require() at the same time, it does not work. You either use require() or import And, your package.json module type or file extension must match the type of import you are using

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论