Why isn't my React running after I compile with Babel?

Why isn't my React running after I compile with Babel?
0

#1

I’ trying to build an extremely simple app to show the message ‘success’ in the browser.

After I do npm run build it compiles to ../dist/index.js.

Im using live reload on vsCode to run index.html in the browser and I’m still failing. What am I missing or doing wrong?

I’m trying to only use babel instead of webpack or react-scripts

./publc/index.html

<html>
<body>
    <div id="root"></div>
    <script src="../dist/index.js"></script>
</body>
</html>

./src/index.js

import ReactDOM from 'react-dom';
import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div>success</div>
         );
    }
}

ReactDOM.render(<App/>, document.querySelector('#root'))

.babelrc

{"presets": [
    "env", "react"
]}

package.json

{
  "name": "doms-app",
  "scripts": {
    "build": "babel src -d dist -w"
  },
  "devDependencies": {
    "babel-preset-react": "^6.24.1",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-preset-env": "^1.7.0"
  },
  "license": "ISC",
  "dependencies": {
    "react": "^16.5.2",
    "react-dom": "^16.5.2"
  }
}


#2

If you aren’t using webpack. You can run babel through @babel/cli which is in the terminal.

Take a look at this doc.

Although I suggest you install webpack to run it easily.


#3

No offence but you people should read questions carefully before responding.

Compiling isn’t my problem. I can’t get my compiled code to work with index.html so that it shows the message that I want it to show.

I don’t want to use webpack because I’m learning and I want to know how to do it with babel.


#4

No offence but you people should read questions carefully before responding.

Well, probably a better explanation would have been helpful^^

Your problem seems related to the require statement, used by Babel in the compiled file.

You probably want to use ‘Browserify’ to have access to require (which is not available in the browser).

install it with

npm install browserify

and add the script ( i added one script for sake of clarity, you can do all in the same command )

“scripts”: {
“build”: “babel src -d dist”,
“browserified-build”: “browserify dist/index.js -o dist/index2.js”
}

use index 2 in your html and it should works ^^