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

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.

主站蜘蛛池模板: 永川市| 涿州市| 陈巴尔虎旗| 筠连县| 钟山县| 自贡市| 耿马| 三原县| 漳浦县| 吉木萨尔县| 阿合奇县| 中山市| 临汾市| 江北区| 历史| 汨罗市| 红河县| 临江市| 元谋县| 东乡| 文安县| 房产| 昌乐县| 那坡县| 买车| 昌江| 湘西| 柳林县| 永丰县| 大足县| 淮阳县| 和硕县| 乌拉特中旗| 吴川市| 巫山县| 兖州市| 建瓯市| 滁州市| 乌审旗| 米林县| 三台县|