官术网_书友最值得收藏!

Moving our React

Enough of console logs; now, let’s use Webpack to take care of some useful code:

  1. 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.
  2. 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'))
  1. 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.
  2. 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.
  3. 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!

  1. 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.

主站蜘蛛池模板: 丹阳市| 加查县| 竹溪县| 南江县| 南乐县| 文山县| 治多县| 滨州市| 永平县| 墨江| 台东县| 墨玉县| 龙口市| 黔南| 宁海县| 武宁县| 苍山县| 南乐县| 上蔡县| 社旗县| 阳谷县| 金溪县| 德庆县| 兰坪| 阳城县| 伊宁县| 霍林郭勒市| 广汉市| 横山县| 若羌县| 抚顺市| 瑞金市| 克东县| 阿尔山市| 馆陶县| 宜州市| 亳州市| 昌图县| 华容县| 磐安县| 盐山县|