Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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" />

test1.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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!";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading