0
votes

I am new to React. I have added it to a project using the information on this site:

https://reactjs.org/docs/add-react-to-a-website.html

Run npm init -y (if it fails, here’s a fix)

Run npm install babel-cli@6 babel-preset-react-app@3

Then,

npx babel --watch src --out-dir . --presets react-app/prod

Whenever I try adding a module it gives me:

Uncaught SyntaxError: Cannot use import statement outside a module.

Here is how I am importing :

import { PostcodeLookup } from "@ideal-postcodes/postcode-lookup" 

(I've tried this at the top of my react js file and in a seperate script file called in a componentDidMount() method via:

 const script = document.createElement("script");

script.src = "my_script.js";
script.async = true;

document.body.appendChild(script);

Thank you.

4

4 Answers

1
votes

Where is the import React from 'react' statement, and how is that js file connected to your html? If you are linking the file containing this code from a <script> tag in your HTML, you need to give that script tag a type="module" attribute.

1
votes

Notice how in the page you linked there's no reference to imports or exports.
Also how that page says:

Tip
We’re using npm here only to install the JSX preprocessor;

This means it will only process JSX expressions into React.createElement function calls. If you want to use modules, you will either need to use native modules by changing the type of your <script to module

<script type="module" src="./main.js">

or use a bundler.

To use a bundler, check out the next page of the React tutorials: https://reactjs.org/docs/create-a-new-react-app.html

0
votes

The steps you mentioned are for jsx setup. Can you paste complete error message ? Have you installed React in your existing project ?

You perhaps have to install React to make it work.

-1
votes

With export class Arrow... you have to use import {Arrow}... whereas with export default class Arrow... you have to use import Arrow.... In the former case, there might be multiple export... statements in a file and therefore your import statement has to be able to handle importing multiple variables by placing that potential list of variables in braces. With export default... there can be only a single export from that file and therefore the import statement can confidently assert that it is importing a single variable, i.e. import myVariabl