When I include an external javascript file into my Html file, I meet the error messages Uncaught SyntaxError: Unexpected token ‘export’ & Uncaught SyntaxError: Cannot use import statement outside a module. This article will tell you how to fix these 2 errors.
1. How To Fix The Javascript Error Uncaught SyntaxError: Unexpected token ‘export’ & Uncaught SyntaxError: Cannot use import statement outside a module.
- My javascript file source code uses the ES6 syntax as below, below js file name is test1.js.
export default function helloFromTest3(){ console.log('hello world'); } export const moduleName = 'test';
- The above js file defines a js module, but I include it in my Html file using the below code.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>How To Fix Javascript Uncaught SyntaxError: Unexpected token 'export' & Uncaught SyntaxError: Cannot use import statement outside a module</title> <script type="text/javascript" src="./js/test1.js" charset="utf-8"></script> </head> <body> </body> </html>
- I upload the above Html file and js file to a local webserver to browse, if you browse it through the local file it may throw errors ( please refer How To Fix Error Access To Script At From Origin ‘null’ Has Been Blocked By Cors Policy: Cross Origin Requests Are Only Supported For Protocol Schemes: Http, Data, Chrome, Chrome-extension, Chrome-untrusted, Https).
- When I open the above Html file in a web browser with the local web server URL like http://localhost:8000/index-import-multiple-js-files.html the error happens. I can find the error message in the web browser inspector console window.
- I finally find the method to fix this error, that is to change the code <script type=”text/javascript” src=”./js/test1.js” charset=”utf-8″></script> to <script type=”module” src=”./js/test1.js” charset=”utf-8″></script>.
- Because the code in the test1.js defines an ES6 module, then you need to specify the js file type as a module but not text/javascript like below Html source code, then the error is fixed.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>How To Fix Javascript Uncaught SyntaxError: Unexpected token 'export' & Uncaught SyntaxError: Cannot use import statement outside a module</title> <script type="module" src="./js/test1.js" charset="utf-8"></script> </head> <body> </body> </html>