- 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.
推薦閱讀
- 數據科學實戰手冊(R+Python)
- 多媒體CAI課件設計與制作導論(第二版)
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- Computer Vision for the Web
- Learning Selenium Testing Tools with Python
- Instant Apache Stanbol
- C#程序設計(慕課版)
- Java游戲服務器架構實戰
- 數據結構(C語言)
- Nginx Lua開發實戰
- Multithreading in C# 5.0 Cookbook
- Programming with CodeIgniterMVC
- Docker:容器與容器云(第2版)
- Learning Kotlin by building Android Applications
- Mastering Drupal 8