簡體   English   中英

用純 JS 將一個 JS 文件導入另一個

[英]Import one JS file into another in plain JS

所以讓我們假設我有兩個 js 腳本

script1.js

export default function Hello() {
     return "Hello buddy!";
}

script2.js

import { Hello } from './script1.js';

function print(){
     let val = Hello;
     console.log(val);
}

當我在瀏覽器中運行打印功能時,出現以下錯誤

Uncaught SyntaxError: Cannot use import statement outside a module

Unexpected token 'export' 

我做了一些調查,通過向 script2.js 添加類型模塊來解決這個問題。 但問題是。 我沒有 HTML 來更改腳本。 我用香草 javascript 做所有事情。 那么,是通過 ID 獲取腳本並將 script2.js 的類型從 text/javascript 更改為模塊的解決方案嗎?

有沒有其他方法可以將 script2.js 更改為模塊?

您可以添加一個.mjs文件。

例子

// index.js

import otherFile from './otherFile.js';
// otherFile.js

import otherOtherFile from './otherOtherFile.mjs';

export default './otherFile.js';
// otherOtherFile.mjs

export default 'otherOtherFile.mjs';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM