从浏览器中的一个 JavaScript 文件导入另一个 JavaScript 文件。

huangapple go评论64阅读模式
英文:

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

&lt;script src=&quot;test1.js&quot; /&gt;

test1.js

import { test_func } from &#39;test2.js&#39;;
console.log(test_func());

test2.js

export function test_func() {
  return &quot;Hi!&quot;;
}

I also tried adding the string &lt;script type=&quot;module&quot; src=&quot;test2.js&quot; /&gt; and &lt;script type=&quot;text/javascript&quot; src=&quot;test2.js&quot; /&gt; 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:

&lt;script src=&quot;./test1.js&quot; type=&quot;module&quot;&gt;&lt;/script&gt;

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 &#39;./test2.js&#39;;
console.log(test_func());

test2.js is pretty much unchanged:

export function test_func() {
    return &quot;Hi!&quot;;
}

huangapple
  • 本文由 发表于 2023年6月15日 02:19:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定