简体   繁体   English

Javascript 模块在 github 页面上不起作用

[英]Javascript modules don't work on github pages

I build a project with a local server (using live server VS extension), who works fine.我使用本地服务器(使用实时服务器 VS 扩展)构建了一个项目,该项目工作正常。

In this project, I'm using javascript modules, so in index.html, I have:在这个项目中,我使用 javascript 模块,所以在 index.html 中,我有:

<script src="js/index.js" type="module"></script>

And in index.js:在 index.js 中:

import {} from "/js/home.js";
import {} from "/js/filter.js";
import {} from "/js/scroll.js";

The issue come when I try to display the website using github pages.当我尝试使用 github 页显示网站时,问题就来了。 JS files seems not found and browser console return:似乎找不到 JS 文件,浏览器控制台返回:

home.js:1 Failed to load resource: the server responded with a status of 404 () filter.js:1 Failed to load resource: the server responded with a status of 404 () home.js:1 资源加载失败:服务器响应状态为 404() filter.js:1 资源加载失败:服务器响应状态为 404()

I tried to change paths with no success, and I have no idea why all works good locally but not with github pages我尝试更改路径但没有成功,而且我不知道为什么在本地一切正常但在 github 页面上却不行

Maybe dot in path helps you import {} from "./js/home.js";也许路径中的点可以帮助您import {} from "./js/home.js";

As a relatively new coder, I had the same problem with my JavaScript modules.作为一个相对较新的编码器,我的 JavaScript 模块也遇到了同样的问题。

My page worked in my local live server and wouldn't deploy on GitHub.我的页面在我的本地实时服务器上工作,不会部署在 GitHub 上。

It may be that the path you used is not pointing to the proper location where your JS script is.可能是您使用的路径没有指向您的 JS 脚本所在的正确位置。 Perhaps you need to use the relative path with the dot in front of the forward slash like ./ instead of /也许您需要使用正斜杠前面带点的相对路径,例如./而不是/

This way, it points to your local repository folder.这样,它指向您的本地存储库文件夹。

I think if you just set it as the forward slash / , it points to your root directory of your GitHub pages instead of your local repository.我想如果你只是将它设置为正斜杠/ ,它指向你的 GitHub 页面的根目录而不是你的本地存储库。

In my case, my web page loaded correctly after I changed my script source in my index.html from:在我的例子中,我的 web 页面在我更改我的index.html中的脚本源后正确加载:

<script type="module" src="/js/main.js"></script>

To:到:

<script type="module" src="./js/main.js"></script>

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

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