So I'm trying to import another file in JS and I keep getting errors. The main file is script.js
and I'm trying to import CookieManager.js
. I first tried using
var cookies = require('/CookieManager.js');
but that caused this error: Uncaught ReferenceError: require is not defined
. I found out that this happends because require
is only supported by Node.js and therefore is causes an error when trying to run it in a browser. I then tried using
import {getCookie} from "../CookieManager";
and set it as an export function which caused this:
Uncaught SyntaxError: Cannot use import statement outside a module
. To fix that, I changed the type of the file from text/javascript
to module
in HTML. This happened: net::ERR_ABORTED 404 (Not Found)
. Finally, I tried using
JQuery (`$.getScript('/CookieManager.js', function()`)
but that also resulted in an error:
jquery.min.js:2 GET http://localhost:63342/CookieManager.js?_=1591679474637 404 (Not Found)```
Try:
In package.json
add:
{"type": "module"}
Then in CookieManager.js
:
export function GetCookie() { // your code to import}
Then script.js
:
import { GetCookie } from '../CookieManager.js';
Here is the directory structure:
├───HomePage
│ ├index.html
│ ├style.css
│ ├script.js
├CookieManager.js
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.