Hi,
I am trying to configure https://docs.amplify.aws/lib/analytics/getting-started/q/platform/js#configure-your-app in my reactive web app on Platform version 11. I have added a script under scripts folder and here is the code in the script:
import Amplify from 'aws-amplify';
import awsconfig from './aws-exports';
Amplify.configure(awsconfig);
On my home screen I have added this script as the required script. When I try to run the app, I see below error on the console:
uncaught syntaxerror cannot use import statement outside a module react
Has anyone faced similar issue? Am I doing it the wrong way?
Thanks in advance for any help or suggestions here.
Hi Akshay.
It seems like this error is coming from the type of tag <script> added to your code, when importing something the tag should have the type="module".
I don't know if there is a better way, but in the onInitialize of your page, you could add a JS script that create your own script tag, with the correct type, something like this.
var head1 = document.getElementsByTagName('head')[0];var script_src1= "URL for your import script";var new_script1 = document.createElement('script');new_script1.type = 'module';new_script1.src= script_src1;head1.appendChild(new_script1);
The credit for this script goes to Fábio Fantato in this comment
Hope this helps.
Best regards.
To solve the error, set the type attribute to module when loading the script in your HTML code. When working with ECMAScript modules and JavaScript module import statements in the browser, you'll need to explicitly tell the browser that a script is module. To do this, you have to add type="module" onto any ‹script› tags that point to a JavaScript module. Once you do this you can import that module without issues.
script type="module" src="./index.js"
If you are working on Node.js or react applications and using import statements instead of require to load the modules, then ensure your package.json has a property "type": "module" as shown below.
{
// ...
"type": "module",
}
Moreover, In some cases, you may have to use both import and require statements to load the module properly.
// import { parse } from 'node-html-parser';
parse = require('node-html-parser');
This error "Cannot use import statement outside a module " can happen in different cases depending on whether you're working with JavaScript on the server-side with Node.js , or client-side in the browser. There are several reasons behind this error, and the solution depends on how you call the module or script tag.
Hi @Akshay Puri,
Did you solved the problem? Actually im trying to do the same.
Best Regards.