简体   繁体   English

无法在 express 中加载 javascript 文件

[英]Unable to load javascript files in express

I am making an express web app and I am unable to import a javascript file.我正在制作一个快速的网络应用程序,但我无法导入一个 javascript 文件。

In board.js , I have a line const utility = require('./utility');board.js ,我有一行const utility = require('./utility'); . . This statement gives an error: ReferenceError: require is not defined .此语句给出错误: ReferenceError: require is not defined

VSCode suggests to convert const utility = require('./utility'); VSCode 建议转换const utility = require('./utility'); to an ES6 module.到 ES6 模块。 The result after accepting that suggestion is: import { generateRandomData } from './utility';接受该建议后的结果是: import { generateRandomData } from './utility'; . .

If I do this, the previous error goes away but a new error appears SyntaxError: import declarations may only appear at top level of a module .如果我这样做,之前的错误就会消失,但会出现一个新错误SyntaxError: import declarations may only appear at top level of a module

This is the folder structure of the project:这是项目的文件夹结构:

在此处输入图片说明

server.js : server.js

const express = require("express");
const app = express();
const path = require('path');

const PORT = process.env.PORT || 5000

app.listen(PORT, () => {
    console.log("server started")
});

app.use(express.static(path.join(__dirname + '/public')))

app.get('/', (req,res) => {
    res.sendFile(__dirname + "/index.html")
});

utility.js : utility.js

const hello = () => {
    console.log('hello');
}

module.exports.hello = hello;

How else am I supposed to import javascript files in board.js ?我还应该如何在board.js导入 javascript 文件?

Your public directory is made static via express.static in your server.js.您的公共目录通过 server.js 中的 express.static 成为静态的。 Therefore, calling a public file from client-side will not pass by express but by the client's browser.因此,从客户端调用公共文件不会通过 express 而是通过客户端的浏览器。

If your JS is played directly within a browser, instead of require you should use import and export .如果你的 JS 直接在浏览器中播放,你应该使用import 和 export而不是 require 。

<script src="utility.js"></script>

I added this line in index.html and it solved the problem.我在 index.html 中添加了这一行,它解决了问题。

Edit: Sorry, I thought I pasted the line.编辑:抱歉,我以为我粘贴了该行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM