简体   繁体   中英

react export Unexpected token

So I have these file and folder.

App.js
modules/
  user/
    index.js
    list.js

In list.js I have export default (props) => (...)

In index.js I have export UserList from './list';

And in App.js I have import { UserList } from './modules/user';

Is there something wrong there? Because I got

./src/modules/user/index.js
Syntax error: Unexpected token, expected { (1:7)
> 1 | export UserList from './list';

But I don't see what's wrong here? Help!

Edit: Here's more details of my list.js file, but I don't think it makes a difference because the error is in index.js

import React from 'react';
// more import
export default (props) => (
  <List {...props}>
    ...
  </List>
);

I see you are exporting the component directly which belongs to another file without importing it.

The way you are doing it is a ES8 Proposal

In ES6, you could export the component as

 export {default as UserList} from './list'

and then import as

import { UserList } from './modules/user';

For Babel 6 users

add babel-plugin-transform-export-extensions plugin to your .babelrc like this:

  "plugins": [
    "babel-plugin-transform-export-extensions",
    "transform-es2015-modules-commonjs"
  ]

and then run to the following install the plugins

npm install --save-dev babel-plugin-transform-export-extensions
npm install --save-dev babel-plugin-transform-es2015-modules-commonjs

After this, export of modules will work in the following way from index.js:

export simpleRestClient from './simple';
export jsonServerRestClient from './jsonServer';
export * from './types';

For those using earlier babel versions, simply use the commonjs module.

I added <script type="module" src="/Aapp.js"></script> in inside of body section of public/index.html . It worked for me. Please refer this blog .

I used node version 18.12.1 and react version 17.0.2

<!DOCTYPE html>  
<html lang="en">  
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>

    <!-- ✅ set this script’s type to `module` -->
    <script type="module" src="/Aapp.js"></script>
  </body>
</html>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM