skip to Main Content

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.

2

Answers


  1. try writing the path to the file. Like => src="./test2.js" ( if test2.js test is in the same folder as the index)

    Login or Signup to reply.
  2. 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!";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search