![](/img/trans.png)
[英]How do I correctly export and import a plain JS file into another JS file?
[英]How do I import another file in JS?
所以我試圖在 JS 中導入另一個文件,但我不斷收到錯誤。 主文件是script.js
,我正在嘗試導入CookieManager.js
。 我第一次嘗試使用
var cookies = require('/CookieManager.js');
但這導致了這個錯誤: Uncaught ReferenceError: require is not defined
。 我發現這是因為require
僅受 Node.js 支持,因此在嘗試在瀏覽器中運行它時會導致錯誤。 然后我嘗試使用
import {getCookie} from "../CookieManager";
並將其設置為導出 function 導致此:
Uncaught SyntaxError: Cannot use import statement outside a module
. 為了解決這個問題,我將文件的類型從text/javascript
更改為 HTML 中的module
。 這發生了: net::ERR_ABORTED 404 (Not Found)
。 最后,我嘗試使用
JQuery (`$.getScript('/CookieManager.js', function()`)
但這也導致了錯誤:
jquery.min.js:2 GET http://localhost:63342/CookieManager.js?_=1591679474637 404 (Not Found)```
嘗試:
在package.json
添加:
{"type": "module"}
然后在CookieManager.js
中:
export function GetCookie() { // your code to import}
然后script.js
:
import { GetCookie } from '../CookieManager.js';
這是目錄結構:
├───HomePage
│ ├index.html
│ ├style.css
│ ├script.js
├CookieManager.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.