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

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.

主站蜘蛛池模板: 青铜峡市| 武隆县| 苏尼特左旗| 久治县| 中阳县| 郓城县| 郓城县| 宁都县| 永泰县| 东台市| 穆棱市| 四子王旗| 阳朔县| 达拉特旗| 临潭县| 永福县| 昌黎县| 鲜城| 马关县| 麻栗坡县| 东丽区| 清水县| 南阳市| 准格尔旗| 巴楚县| 砚山县| 句容市| 山东省| 巴林右旗| 恩平市| 宁海县| 剑阁县| 南汇区| 色达县| 曲周县| 柘荣县| 乐山市| 阜新| 三门县| 遂昌县| 仁化县|