简体   繁体   中英

“Uncaught SyntaxError: Cannot use import statement outside a module” after babel compilation

Im using this docs https://reactjs.org/docs/add-react-to-a-website.html#run-jsx-preprocessor to add a React component with JSX to my website. I run this command to compile:

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

And I get this error in chrome console:

Uncaught SyntaxError: Cannot use import statement outside a module

Which comes from this line in the compiled file: import _regeneratorRuntime from 'babel-runtime/regenerator';

I don't get it- in the docs they state that you can use babel just like a CSS preprocessor, but here it seems that _regeneratorRuntime depends on the node_module folder, but i'm not planing to run npm i in production, it is only to compile my JSX to a.js file which should be a standalone file any browser can run.

In package.json:

"dependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-react-app": "^3.1.2"
  }

In HTML footer:

<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<script type="text/javascript" src="/js/react-components/index.js"></script> <!-- index.js compiled from src/index.js -->

You need to create a babelrc file in your project or simply run this command npm install --save-dev @babel/preset-react Also add this code: { "presets": ["@babel/preset-react"] }

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