什么是使用把手引用CSS和JS文件的正确方法?

什么是使用把手引用CSS和JS文件的正确方法?

问题描述:

我目前正在为我的项目使用express和handlebars。这是我使用车把的第一次,我无法弄清楚如何正确地引用我的CSS和JS文件什么是使用把手引用CSS和JS文件的正确方法?

的位置

我目前的项目结构如下图所示

- test (root) 
    -views 
    -js 
     -some JS files 
    -css 
     -some css files 
    -layout 
     -main.handlebars 
    - servers.js (my server) 

所以我在主体并以下.handlebars布局文件

<!Doctype html> 
<html> 
<head> 
    <title></title> 
    {{#each css}} 
     <link rel="stylesheet" href="../css/{{this}}"> 
    {{/each}} 
</head> 
<body> 
    {{{body}}} 
    {{#each js}} 
     <script src="../js/{{this}}"></script> 
    {{/each}} 
</body> 
</html> 

而且里面{{this}},index.css去在CSS和index.js进去的JS。

但是这给了Cannot GET 404 http://localhost:8000/js/index.js错误。所以我想也许把柄从根看起来不知何故。所以我试图

<!Doctype html> 
<html> 
<head> 
    <title></title> 
    {{#each css}} 
     <link rel="stylesheet" href="views/css/{{this}}"> 
    {{/each}} 
</head> 
<body> 
    {{{body}}} 
    {{#each js}} 
     <script src="views/js/{{this}}"></script> 
    {{/each}} 
</body> 
</html> 

但是这给了Cannot GET 404 http://localhost:8000/views/js/index.js错误时,它看起来是该文件的正确位置。

在把手中引用js和css文件的正确方法是什么?

您应该创建公用目录,并且在服务器中可以提供静态文件,如图像,CSS文件和JavaScript文件,请使用Express中的express.static内置中间件功能。

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

enter image description here

现在,你可以加载在公共目录下的文件:

<!Doctype html> 
<html> 
<head> 
    <title></title> 
    {{#each css}} 
     <link rel="stylesheet" href="/css/{{this}}"> 
    {{/each}} 
</head> 
<body> 
    {{{body}}} 
    {{#each js}} 
     <script src="/js/{{this}}"></script> 
    {{/each}} 
</body> 
</html> 
+0

是...我很愚蠢 – forJ