简体   繁体   中英

How to import variable from another html file? (I use import/export, but error occurs)

//test_1.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="utf-8" />
    <title>DB Test</title>
</head>
<body>
    <script type="module">
        var num = 1;
        console.log(num)

        export {num}
    </script>
</body>
</html>
//test_2.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="utf-8" />
    <title>DB Test</title>
</head>
<body>
    <script type="module">
        import {num} from './test_1.html'
        console.log(num)
    </script>
</body>
</html>

I want to use variable named num in test_1.html and test_2.html, but when I open test_2.html, error like 'test_1.html:1
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.' occurs and console.log(num) at test_2.html doesn't work properly. How can I import/export properly?

You can't import from an HTML file in this manner.

Is it possible for you to move the modules into separate JS files such as test_1.js and test_2.js then have test_2.js import from test_1.js instead?

EDIT

Like this:

<!-- test_1.html -->

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="utf-8" />

        <title>DB Test</title>
    </head>
    <body>
        <script type="module" src="/test_1.js"></script>
    </body>
</html>
// test_1.js
var num = 1;

console.log(num);

export { num };
<!-- test_2.html -->

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="utf-8" />
        
        <title>DB Test</title>
    </head>
    <body>
        <script type="module" src="/test_2.js"></script>
    </body>
</html>
// test_2.js
import { num } from "./test_1.js";

console.log(num);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM