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

Welcome to Webpack

Our goal for this section is to take the JavaScript sitting in our script tag in our index.html (the line responsible for rendering our "Hello from React!") and move that to a JavaScript file in the src folder, which is then bundled and injected into the HTML by Webpack.

It sounds complicated, but it’s simpler than it sounds, thanks to the magic of Webpack. Let’s get started:

  1. First, we need to install Webpack:
yarn add webpack@3.5.4

If you check the package.json, you should see Webpack listed under our dependencies. For this book, I’ll be using version 3.5.4; if you run into any inexplicable problems, try specifying this version with yarn add webpack@3.5.4:

  1. Now, we need to tell Webpack what to do. Let’s start by moving our React code into the src folder. Inside chatastrophe/src, create a file called index.js.
  2. Then, type in the following code:
console.log(‘hello from index.js!’);

Our goal is to get this greeting to display in our browser console.

  1. Okay, let’s try out Webpack. In your Terminal, type the following:
node_modules/.bin/webpack src/index.js public/bundle.js

Your Terminal should now look like this:

What does this do? Well, it tells Webpack to take the first file and copy it (and everything it needs, that is, every file it requires) into the second file (which Webpack created for us, since it didn’t exist).

If you open up the newly created public/bundle.js, you’ll see a lot of Webpack boilerplate… and at the bottom, our console.log.

Okay, so it works; we can require this file in our index.html to see our console.log, but that's not using Webpack to its full potential. Let’s try something else.

主站蜘蛛池模板: 中卫市| 临朐县| 辽阳市| 始兴县| 荥阳市| 蒙城县| 怀来县| 巩留县| 福贡县| 田东县| 三门县| 汉阴县| 鹰潭市| 鄯善县| 上饶市| 花垣县| 汾西县| 图木舒克市| 松江区| 宝兴县| 新巴尔虎右旗| 中超| 望城县| 东乌珠穆沁旗| 新密市| 漠河县| 胶州市| 弋阳县| 正镶白旗| 佛冈县| 双城市| 共和县| 潞西市| 平塘县| 彰化市| 图木舒克市| 柞水县| 淅川县| 罗江县| 巴青县| 翁牛特旗|