- So the first step inside of index.html is going to be to rip out our script tags
Down below I have one script tag and I’m going to delete the type.
- Make a new file in public called “app.js”
- Create a function and call it greeter
document.write("From greeter function");
- Run this through a web pack I can do this from the terminal using the web pack command and it takes two arguments one the location of my root file.
So I’m going to specify a dot forward slash public forward slash app.js and this is the first argument from webpack.
The second argument is where you want to put that bundled file. I want to put it inside of the public folder and I am going to call it bundle.js.
- Go to localhost:3000 to check
- The next thing I am going to do is create my first separate component
I am going to make a new folder call it components and inside of hereI can store individual components in their very own files. Let’s go ahead and create one for Greeter component.
Now I create a file called Greeter.js.
- And inside of the Greeter.js, all I am going to do is move Greeter functionality by cutting and pasting it
The point here isn’t to illustrate a practical example like this. The point is to show how you can have a separate files that are able to load and use each other.
- Now inside a Greeter.js, I have to set module.exports equal to the thing I want other users of the file to be able to access
And this case if someone wants to use Greeter component, all I need to give them is the greeter function just like this. By setting a module that exports equal to greeter, anybody who requires this file will get access to this function.
module.exports = greeter;
- In app.js, instead of defining the function inlin, I can load it from the separate file I just created
To do this I am going to first create a variable which will store the output. I am going to set it equal to require. And then inside of quotes I am going to specify the path which is (‘./components/Greeter’);
var greeter = require('./components/Greeter')
- I’m going to enter a rerun web pack restart my server using the up arrow key twice again
- Into the browser, refresh the page and this time you can see Greeter function still prints. Only this time it’s in a separate file which is really awesome.
This is going to let us break out all of code into its own file and making testing and maintaining our project easier.
So with this in place now that I understand how to load in files : Using require I can move on to refactoring my actual app.jsx file.