简体   繁体   中英

Failed to resolve module specifier "babel-runtime/regenerator"

I'm following the instructions for this link. https://reactjs.org/docs/add-react-to-a-website.html

I have the following code and it works:

const domContainers = document.querySelectorAll('[name="uiattr"]');

domContainers.forEach((element) => {
  const id = element.id.split("-")[1];
  ReactDOM.render(e(LikeButton), element);
});

If i change it to this code and add async to it:

const domContainers = document.querySelectorAll('[name="uiattr"]');

domContainers.forEach(async (element) => {
  const id = element.id.split("-")[1];
  const attr = await getAttr(id);
  ReactDOM.render(e(LikeButton), element);
});

i get the following error in the console with nothing else: Failed to resolve module specifier "babel-runtime/regenerator"

I installed bable like this: npm install babel-cli@6 babel-preset-react-app@3

and i deploy with this command: js-dev$ npx babel --watch src --out-dir../prj/static/prj/js/ --presets react-app/prod

I am new to the babel world, i'm assuming i need something else, but have no idea. I'm assuming the syntax is correct, only because its compiling without error. Something i've seen babel fail on when i have it wrong.

The React tutorial is indeed very confusing and doesn't cover all aspects.

I would suggest to just install react & react-dom : npm install --save react react-dom

You will need webpack to bundle your code and babel + a couple of plugins to compile your JSX, use async functions, ...: npm install --save-dev @babel/core @babel/preset-env @babel/preset-react @babel/plugin-transform-runtime babel-loader webpack webpack-cli .

Create a webpack.config.js file in your root folder:

const path = require('path');

module.exports = {
    mode: "development", // or production
    entry: {
        app1: './react/app1/index.js'
    },
    watch: true,
    output: {
        filename: "[name].js",
        path: path.join(__dirname, "public/react")
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                }
            }
        ]
    }
};

Create a .babelrc file in your root folder:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": ["@babel/plugin-transform-runtime"]
}

Example react/app1/index.js file:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("myContainer"));

Write your react code in./react/app1/index.js (you can import other React files, modules, ...)

Then in your html just put a script tag: <script src="public/react/app1.js"></script>

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