[英]JS import statement from another folder
I am trying to learn more JS and at the same time convert a older sites menu that is using jQuery for the menu.我正在尝试学习更多 JS,同时转换使用 jQuery 作为菜单的旧站点菜单。
In the current structure the menu.js file is in js
directory relative to the index.html file.在当前结构中,menu.js 文件位于相对于 index.html 文件的
js
目录中。
This is an abbreviation of the current code of index.html:这是 index.html 当前代码的缩写:
<nav>
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
</nav>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/menu.js"></script>
<script>
$(function() {
menu.init();
});
</script>
What I want is to have a main.js file in the js
directory and then use a import statement to import the menu.js file which is located in a lib directory within the js
directory.我想要的是在
js
目录中有一个 main.js 文件,然后使用 import 语句导入位于js
目录中 lib 目录中的 menu.js 文件。
What I changed in the index.html file is that it now points to the main.js file instead in the js
directory.我在 index.html 文件中更改的是它现在指向 main.js 文件而不是在
js
目录中。
<script type="module" src="js/main.js"></script>
In the main.js file I tried the following:在 main.js 文件中,我尝试了以下操作:
import 'lib/menu.js';
This didn't work out, and I wonder also if its possible to have this part in the index.html file, the这没有成功,我还想知道是否可以在 index.html 文件中包含这部分,
$(function() {
menu.init();
});
done in the main.js file instead?在 main.js 文件中完成?
I think you need export what you want be visible inside menu.js, and import inside main.js.我认为您需要导出您希望在 menu.js 中可见的内容,并在 main.js 中导入。
menu.js菜单.js
export { variableName1, variableName2 };
const variableName1 = 'Hey1';
const variableName2 = 'Hey2';
main.js主文件
import { variableName1, variableName2 } from './js/menu.js';
Better explanation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules更好的解释在这里: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
Plunker: https://plnkr.co/edit/FfMbHbyhyppUSpKC?preview Plunker: https ://plnkr.co/edit/FfMbHbyhyppUSpKC ? preview
I believe the problem is with the import path我相信问题出在导入路径上
import 'lib/menu.js';
This is an absolute path, and your program will be looking for a lib folder in your root directory.这是一个绝对路径,您的程序将在您的根目录中查找 lib 文件夹。
You want to use a relative path.您想使用相对路径。 If your main.js file is in the same folder as the lib folder, the path would look like
如果您的 main.js 文件与 lib 文件夹位于同一文件夹中,则路径将如下所示
import './lib/menu.js'
where './' represents the current folder.其中“./”代表当前文件夹。 If you needed to go back one level, '../' will go to the parent folder, and so on.
如果您需要返回一级,“../”将转到父文件夹,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.