英文:
import js file from another js file in browser
问题
I'm trying to import a test1.js file into html that imports the test_func function from test2.js, but it doesn't work, browser doesn't make request for test2.js.
test.html
<script src="test1.js"></script>
test1.js
import { test_func } from 'test2.js';
console.log(test_func());
test2.js
export function test_func() {
  return "Hi!";
}
I also tried adding the string <script type="module" src="test2.js"></script> and <script type="text/javascript" src="test2.js"></script> to the beginning of the test.html file, but that didn't work.
英文:
I'm trying to import a test1.js file into html that imports the test _func function from test2.js, but it doesn't work, browser doesn't make request for test2.js
test.html
<script src="test1.js" />
test1.js
import { test_func } from 'test2.js';
console.log(test_func());
test2.js
export function test_func() {
  return "Hi!";
}
I also tried adding the string <script type="module" src="test2.js" /> and <script type="text/javascript" src="test2.js" /> to the beginning of the test.html file, but that didn't work.
答案1
得分: 1
尝试编写文件路径,例如 => src="./test2.js"(如果test2.js文件与索引文件在同一文件夹中)。
英文:
try writing the path to the file. Like => src="./test2.js" ( if test2.js test is in the same folder as the index)
答案2
得分: 1
在index.html中使用:
<script src="./test1.js" type="module"></script>
在test1.js中,请确保使用相对于当前文件的路径./(以便解释器不会将它们混淆为命名的node_modules导入包),如下所示:
import { test_func } from './test2.js';
console.log(test_func());
test2.js基本保持不变:
export function test_func() {
    return "Hi!";
}
英文:
In index.html use:
<script src="./test1.js" type="module"></script>
in test1.js make sure to use paths relative to the current file ./ (so that the interpreter does not confuses them as named node_modules imports, packages) like:
import { test_func } from './test2.js';
console.log(test_func());
test2.js is pretty much unchanged:
export function test_func() {
    return "Hi!";
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论