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

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.

主站蜘蛛池模板: 宝兴县| 阳曲县| 峨山| 紫阳县| 拉萨市| 利川市| 称多县| 轮台县| 皋兰县| 新安县| 扎鲁特旗| 西平县| 延川县| 中江县| 北海市| 德庆县| 濮阳县| 婺源县| 西青区| 外汇| 马公市| 临桂县| 遵义市| 界首市| 孟村| 隆尧县| 邵阳县| 娱乐| 常州市| 永善县| 屏东市| 铁力市| 平利县| 澄江县| 奈曼旗| 疏附县| 塔河县| 渭南市| 沙田区| 珲春市| 右玉县|