本文介绍了从另一个js文件导入函数。使用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于在javascript中包含文件的问题。
我有一个非常简单的例子:
- > index.html
- > model
- > course.js
- > student.js
course.js:
function Course(){
this.id ='';
this.name ='';
}
学生有课程资产。像这样:
import'./course';
function Student(){
this.firstName ='';
this.lastName ='';
this.course = new Course();
}
,index.html如下:
< html>
< head>
< script src =./ models / student.jstype =text / javascript>< / script>
< / head>
< body>
< div id =myDiv>
< / div>
< script>
window.onload = function(){
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv')。innerHTML = x.course.id;
}
< / script>
< / body>
< / html>
但是我收到错误var x = new Student();:
当我从学生中删除导入,我不再收到错误。
我曾尝试使用(要求,导入,包含,创建自定义函数,导出),但没有一个对我有效。
有谁知道为什么?以及如何解决这个问题?
P.S。路径是正确的,它来自VS代码的自动完成
解决方案
以下适用于Firefox和Chrome。在Firefox中,它甚至可以从文件:///
导出功能课程(){
this.id ='';
this.name ='';
};
从'./course.js'导入{课程};
导出函数学生(){
this.firstName ='';
this.lastName ='';
this.course = new Course();
};
When I remove the import from Student, I don't receive the error anymore.I have tried to use (require, import, include, create a custom function, export) and none has worked for me.
Anybody knows why? and how to fix that?
P.S. the path is correct, it is come from the autocomplete from VS Code
解决方案
The following works for me in Firefox and Chrome. In Firefox it even works from file:///
export function Course() {
this.id = '';
this.name = '';
};
import { Course } from './course.js';
export function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
};
<div id="myDiv">
</div>
<script type="module">
import { Student } from './models/student.js';
window.onload = function () {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
这篇关于从另一个js文件导入函数。使用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!