- Progressive Web Apps with React
- Scott Domes
- 297字
- 2021-07-08 09:36:18
Moving our React
Enough of console logs; now, let’s use Webpack to take care of some useful code:
- Delete our index2.js, and delete all code from index.js. Then, copy and paste our React code into index.js, and delete the first three script tags in the index.html.
- After doing so, you should have only one script tag in your index.html (the one for bundle.js), and your index.js should consist of this line:
ReactDOM.render(React.createElement('h1', false, 'Hello from React!'), document.getElementById('root'))
- Before we run Webpack, though, we have a problem. We deleted the script tags that required React and ReactDOM, but we still need a way to access them in our index.js.
- We can do it in the same way we required index2.js, that is, type out require(‘../node_modules/react/dist/react.js’), but that’s a lot of typing. Also, we will be using many dependencies from node_modules in our code.
- Fortunately, requiring modules in this way is common, so the require function is smart enough to grab a dependency based on the name alone, which means we can add this to the beginning of our index.js:
var React = require('react');
var ReactDOM = require('react-dom');
We can then use these packages in our code, just as before!
- Alright, let’s try it out. Run Webpack again:
node_modules/.bin/webpack src/index.js public/bundle.js
It will show the following output:

Now, you can see all the files that Webpack bundles together in our index.js: React, all its dependencies, and ReactDOM.
Reload the page and you should see that nothing has changed. However, our application is now much more scalable, and we can organize our files a lot better. When we add a dependency, we no longer need to add another <script> tag; we just require it in our code where we're using it.
推薦閱讀
- Software Defined Networking with OpenFlow
- GeoServer Cookbook
- Kubernetes實戰
- Python從小白到大牛
- Arduino開發實戰指南:LabVIEW卷
- JavaScript+jQuery開發實戰
- FFmpeg入門詳解:音視頻流媒體播放器原理及應用
- OpenStack Cloud Computing Cookbook(Fourth Edition)
- 21天學通C++(第6版)
- Hands-On C++ Game Animation Programming
- C語言程序設計實踐教程
- BeagleBone Robotic Projects(Second Edition)
- 人工智能算法(卷1):基礎算法
- IBM Cognos TM1 Developer's Certification guide
- DB2SQL性能調優秘笈