Working on my first React project and kinda new to JS, I am struggling with a very basic issue. I wonder what is the best practice to debug this?
I did create my app with create-react-app and I don't succeed loading an external script. Surprisingly I didn't find any help online or in the doc so far, rather any mention of this being an issue.
At the bottom of public/index.html, if I write:
<script>
console.log('Hello World!');
</script>
=> the console display 'Hello World!', normal, all good!
But if instead I do:
<script type="text/babel" src="../src/js/helloworld.js"></script>
and the helloworld.js file just contains console.log('Hello World!');
=> the console doesn't display anything!
Apparently, type must be "text/babel" or I get a syntax error.
What am I doing wrong ?
My folder structure is:
my-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ └── favicon.ico
│ └── index.html
│ └── manifest.json
└── src
└── App.css
└── App.js
└── App.test.js
└── index.css
└── index.js
└── logo.svg
└── js
└── helloworld.js
You could also make it work if you move your helloworld.js file inside of the public folder, as the server using by create-react-app serves all the assets in the public folder but does not serve src. Here is the documentation
in your index.html
<script type="text/javascript" src="js/helloworld.js"></script>
in your project put the js folder inside of public public/js/helloworld.js
The type should be text/javascript as it let your browser know how to interpret the file. The syntax error, you are getting is due to the fact that create-react-app renders the index.html if the file is not found, and then your browser sees html instead of javascript, hence the error : Uncaught SyntaxError: Unexpected token <
Also create-react-app hides a lot of complexity for you and it is going to be difficult to understand all of what happens behind the scene. If you want to go through the complete tooling system in place you could run npm run eject (but read the docs first :) as it can't be reversed.
The boilerplate (create-react-app) you used to create your project utilizes the node.js development environment, so you should stick to that development workflow - by creating node modules.
So you need to convert helloworld.js to a node module:
exports.helloWorld = function() {
console.log('Hello World!');
};
Then use it in other modules of your application (i.e. index.js):
import { helloWorld } from './js/helloWorld';
helloWorld(); // or call from within a React.js component
You should read about how node.js modules work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With