我试图在所有前端脚本中扎根。
因此,当我想将脚本导入我的index.html
时,我只需要这样做:
<script src="/front/scripts"></script>
第一个问题:
这是我的服务器代码:
app.use('/front/scripts', (req, res) => {
const readScript = (filePath) => {
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) throw err;
return res.write(data);
});
};
readScript('./node_modules/jquery/dist/jquery.js');
readScript('./node_modules/socket.io-client/dist/socket.io.js');
readScript('./src/js/app.js');
});
这是行不通的,因为express正在继续加载页面,因此我无法导入它,因为我的index.html
正在等待front/scripts
停止加载。
第二个问题:
由于文件大小而无法使用,最轻的文件将比jQuery之类的较大文件更快地加载,因此最轻的文件将位于front/scripts
的顶部,而最大的文件将位于<Route path="/car/about-you" component={car} />
的顶部。最轻巧之后。
例如,如果我的个人app.js只是一个3行的jQuery脚本,它更改了div的内容,则由于我的脚本在jQuery之前加载,它将返回一个错误。
如何正确执行此操作?
答案 0 :(得分:1)
一旦所有脚本都已被读取并写入response
,最后response
也必须使用res.end();
来完成
由于readFile
为async
,因此下面的示例有很小的变化,因此无法保证在正确的时间调用res.end()
。做到了synced
。
请参见此处fs.readFileSync。
app.use('/front/scripts', (req, res) => {
const readScript = (filePath) => {
res.write(fs.readFileSync(filePath, 'utf-8'));
};
readScript('./node_modules/jquery/dist/jquery.js');
readScript('./node_modules/socket.io-client/dist/socket.io.js');
readScript('./src/js/app.js');
res.end();
});
答案 1 :(得分:1)
使用express.static
示例:
示例项目设置:
server.js
front
scripts
app.js
server.js:
const express = require('express')
const { join } = require('path')
const app = express()
app.use(express.static(join(__dirname, 'front/scripts'))
app.listen(3000)
您将在这里获得app.js
: localhost:3000 / app.js