使用webpack和Babel设置React环境

Article updated for webpack 2

针对Webpack 2的文章已更新

React is a Javascript library, by Facebook, that is used for building user interfaces. It is a bomb library that offers so many advantages but one of the biggest setbacks is the steep learning curve. When I started out, one of the things that bugged me a whole lot was that most of the tutorials skipped over the React environment set-up.

React是Facebook的Javascript库,用于构建用户界面。 它是一个炸弹库,具有许多优点,但最大的挫折之一就是陡峭的学习曲线。 当我刚开始的时候,困扰我很多的事情之一就是大多数教程都跳过了React环境的设置。

So here we go, this article is best suited for beginners who aren't afraid to get their hands dirty setting up a React environment, from scratch. My number one mission is to keep this article simple and easy to understand. I will not use any boilerplates and you can find the whole set-up on my github repo here. We will be using the following:

因此,开始吧,本文最适合不怕从头开始搭建React环境的初学者。 我的首要任务是使本文简单易懂。 我不会用任何boilerplates,你可以找到整个设置在我的GitHub库在这里 。 我们将使用以下内容:

  1. Webpack - A module bundler

    Webpack-模块捆绑器
  2. Babel - A Javascript compiler

    Babel -Javascript编译器
  3. ES6 - A relatively new Javasript standard

    ES6-相对较新的Javasript标准
  4. Yarn - A package manager

    Yarn-包管理器
  5. React - As expected

    React-如预期

This article is best suited for beginners who aren't afraid to get their hands dirty setting up a React environment from scratch.

本文最适合不怕动手从零开始设置React环境的初学者。

By the end of the tutorial, we will have set-up a working React environment and just for fun we will have a simple webpage displaying Hello World.

在本教程结束时,我们将建立一个可正常工作的React环境,并且仅出于娱乐目的,我们将使用一个简单的网页来显示Hello World。

Brace yourselves for some fun!!

支撑自己,享受乐趣!!

先决条件 ( Pre-requisites )

We require Yarn and Node pre-installed on our machines before we dive into the project.

在进入项目之前,我们需要在计算机上预安装Yarn和Node。

As mentioned above we'll use Yarn Package Manager. It is quite similar to npm and has almost the same commands provided by npm. It also comes with a few extra features that npm does not provide. Just to catch you up, a few of the main reasons I use yarn are:

如上所述,我们将使用Yarn包管理器。 它与npm非常相似,并且具有与npm提供的几乎相同的命令。 它还具有npm无法提供的一些额外功能。 为了赶上您,我使用yarn的一些主要原因是:

  • If you had already installed a package before, you can install it again without any internet connection. Apart from the fact that you can install packages offline, this also increases the speed of your installments.

    如果您以前已经安装过软件包,则可以在没有任何互联网连接的情况下再次安装它。 除了可以脱机安装软件包之外,这还提高了分期付款的速度。
  • The same exact dependencies are installed on any machine. This essentially means that an install on one machine will work the same exact way on any other machine.

    相同的完全依赖项安装在任何计算机上。 这实质上意味着在一台计算机上进行安装将在其他任何计算机上以完全相同的方式工作。

For more information you could go over the Yarn documentation.

有关更多信息,请查阅Yarn文档。

For Mac Os users, the commands below will suffice to install Yarn and because I got all your backs, anyone using any other OS can head on over to the Yarn installation page to get the right instructions on installation.

对于Mac Os用户,以下命令足以安装Yarn,并且由于我的所有支持,因此使用其他操作系统的任何人都可以进入Yarn安装页面以获取正确的安装说明。

> brew update
> brew install yarn

入门 ( Getting Started )

Open your terminal and create a new folder. You can name it as you wish. Navigate into the folder and initialize the project by running yarn init. yarn init just like npm init will give you a few prompts, just press enter till the end or configure it as you'd like to.

打开您的终端并创建一个新文件夹。 您可以根据需要命名。 导航到该文件夹​​并通过运行yarn init初始化项目。 像npm init一样, yarn init会给您一些提示,只需按enter直到最后或根据需要进行配置即可。

> mkdir hello-world-react
> cd hello-world-react
> yarn init

When yarn init is finished you will notice in your folder, in this case 'hello-world-react', you'll have a new file package.json just like if you had done npm init.

yarn init完成后,您会在文件夹中注意到,在本例中为“ hello-world-react”,您将拥有一个新文件package.json ,就像完成npm init

Webpack安装和配置 ( Webpack installation and configuration )

Next, we need to install webpack and a few dependencies.

接下来,我们需要安装webpack和一些依赖项。

> yarn add webpack webpack-dev-server path

Inside 'hello-world-react' a new file yarn.lock is created. This file is what Yarn uses to lock down the exact dependencies to use on another machine, you don't really have to worry about this file as it is automatically generated.

在“ hello-world-react” yarn.lock ,创建了一个新文件yarn.lock 。 该文件是Yarn用来锁定要在另一台计算机上使用的确切依赖项的文件,您不必真正担心此文件,因为它是自动生成的。

Now that we have webpack installed we need a config file to give it instructions on what to do. Create a new file, webpack.config.js, on the project folder and open it on your preferred text editor.

现在我们已经安装了webpack,我们需要一个配置文件来向其提供操作说明。 在项目文件夹上创建一个新文件webpack.config.js ,然后在您首选的文本编辑器上将其打开。

> touch webpack.config.js

We can then update the configuration file:

然后我们可以更新配置文件:

/*
    ./webpack.config.js
*/
const path = require('path');
module.exports = {
  entry: './client/index.js',
  output: {
    path: path.resolve('dist'),
    filename: 'index_bundle.js'
  },
  module: {
    rules: [
      { test: /\.css$/,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" }
        ]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: "babel-loader"
      }, {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: "babel-loader"
      }
    ]
  }
}

Basically, to get a running instance of webpack we need to specify an entry point and an output.

基本上,要获取运行中的webpack实例,我们需要指定一个entry点和一个output

  • entry: Specifies the entry file where the bundler starts the bundling process.

    entry :指定捆绑程序在其中开始捆绑过程的入口文件。
  • output: Specifies the location where the bundled Javascript code is to be saved.

    output :指定捆绑的Javascript代码的保存位置。

We, however, also have loaders. These are needed because we want the browser we use to be able to interprate and run JSX code (for React) and code written in ES6.

但是,我们也有装载机。 这些是必需的,因为我们希望我们使用的浏览器能够插入并运行JSX代码(用于React)和用ES6编写的代码。

  • loaders: They are transformations that are applied on a file in our app.

    loaders :它们是应用于我们应用程序中文件的转换。

The loaders key property takes in an array of loaders. For our basic set-up we specified that the babel-loader goes through and transpiles every file that ends with a .js or .jsx extension excluding the files inside the node_modules folder. You could always add more loaders as needed. For example, if you had separate style sheets in your project you'd require a CSS loader. All these loaders can be found in the webpack documentation. Feel free to test them out.

loaders键属性接受一组加载程序。 对于我们的基本设置,我们指定babel-loader进行检查并转译每个以.js.jsx扩展名结尾的文件, .jsx不包括node_modules文件夹中的文件。 您总是可以根据需要添加更多的装载程序。 例如,如果您的项目中有单独的样式表,则需要CSS加载器。 所有这些加载程序都可以在webpack 文档中找到。 随时对其进行测试。

设置Babel ( Setting up Babel )

In our webpack configuration, we specified that we are using a babel-loader. Where does this babel-loader come from you ask? Well, we need to install it and later set a few configurations.

在我们的webpack配置中,我们指定我们正在使用babel-loader 。 你问这个babel-loader从哪里来? 好吧,我们需要安装它,然后再设置一些配置。

> yarn add babel-loader babel-core babel-preset-es2015 babel-preset-react --dev

Those are all the dependencies we need for Babel. Notice we have installed babel-preset-es2015 and babel-preset-react, presets are Babel plugins that simply tell Babel what to look out for and transform into plain, vanilla Javascript.

这些都是我们对Babel的依赖。 请注意,我们已经安装了babel-preset-es2015babel-preset-react ,预设是Babel插件,它们仅告诉Babel需要注意的内容并转换为普通的原始Javascript。

We then have to configure Babel and we can do this in a new file which we'll name .babelrc.

然后,我们必须配置Babel,我们可以在一个名为.babelrc的新文件中进行此.babelrc

> touch .babelrc

Then we can update the file to:

然后,我们可以将文件更新为:

/* 
    ./.babelrc
*/    
{
    "presets":[
        "es2015", "react"
    ]
}

That is it. Now when babel-loader is called in the webpack config file it knows what to do.

这就对了。 现在,当在webpack配置文件中调用babel-loader时,它知道该怎么做。

设置我们的React组件 ( Setting up our React Components )

So far our file structure looks like this:

到目前为止,我们的文件结构如下所示:

.
|-- node_modules
|-- .babelrc
|-- package.json
|-- webpack.config.js
|-- yarn.lock

Its high time we add the React side don't you think? We'll create a new folder client and add an index.js file and an index.html file.

是时候加入我们的React了,您不觉得吗? 我们将创建一个新的文件夹client并添加一个index.js文件和一个index.html文件。

> mkdir client
> cd client
> touch index.js
> touch index.html
> cd .. 

Now we have this:

现在我们有了这个:

.
|-- client
     |-- index.html
     |-- index.js
|-- .babelrc
|-- package.json
|-- webpack.config.js
|-- yarn.lock

Next we need to add some code. We'll start out with something simple just to verify that our set-up so far works.

接下来,我们需要添加一些代码。 我们将从简单的事情开始,只是为了验证到目前为止的设置是否有效。

Open up index.js and add:

打开index.js并添加:

/*
    ./client/index.js
    which is the webpack entry file
*/
console.log('Hey guys and ladies!!')

Update index.html to:

index.html更新为:

/*
    ./client/index.html
    basic html skeleton
*/
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>React App Setup</title>
  </head>
  <body>
    <div id="root">

    </div>
  </body>
</html>

The index.html is the actual webpage which loads our React Components on the browser. I mentioned before that we need babel in order to compile our code into a syntax that browsers support. We code our React components using JSX and in our case we will also use ES6. The syntax of these two modules is not supported by most browsers therefore, we have to run this code through the babel loaders and then the bundled output is what we'll specify to be displayed on index.html.

index.html是在浏览器上加载我们的React组件的实际网页。 我之前提到过,我们需要babel才能将我们的代码编译成浏览器支持的语法。 我们使用JSX对React组件进行编码,在本例中,我们还将使用ES6 。 大多数浏览器不支持这两个模块的语法,因此,我们必须通过babel loaders运行此代码,然后将绑定的输出指定为显示在index.html上。

One way to add the bundled file to our HTML is to insert a script tag and pass the location of the bundled file into the script tag. A better way to do this is to use this nifty package called html-webpack-plugin. It provides an easy way to have all your HTML generated for you. All you need is the standard HTML skeleton and it'll take care of your script insertions with just a few configurations. Let's do that next.

将捆绑文件添加到我们HTML中的一种方法是插入script标签,然后将捆绑文件的位置传递到脚本标签中。 更好的方法是使用这个名为html-webpack-plugin漂亮软件包。 它提供了一种简便的方法来为您生成所有HTML。 您只需要标准HTML框架,它只需几个配置即可处理您的脚本插入。 接下来,让我们开始。

HTML-Webpack-插件 ( Html-Webpack-Plugin )

First, we'll install the plugin. Make sure your terminal is currently reading you're root project folder, hello-world-react, then enter the following command:

首先,我们将安装插件。 确保您的终端当前正在读取您的根项目文件夹hello-world-react ,然后输入以下命令:

> yarn add html-webpack-plugin

Then open up your webpack.config.js and add a few configurations.

然后打开您的webpack.config.js并添加一些配置。

/* 
    ./webpack.config.js
*/
const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './client/index.html',
  filename: 'index.html',
  inject: 'body'
})

module.exports = {

...

module: {
    rules: [
        ...
    ]
},
// add this line
plugins: [HtmlWebpackPluginConfig]
}

The configuration is pretty self-explanatory. We require the html-webpack-plugin and then create a new instance of it, and set our skeleton HTML as the template. filename refers to the name of the HTML that the plugin will generate. inject body tells the plugin to add any JavaScript into the bottom of the page, just before the closing body tag.

该配置非常不言自明。 我们需要html-webpack-plugin ,然后创建它的新实例,并将我们的框架HTML设置为templatefilename是指插件将生成HTML的名称。 inject主体告诉插件将所有JavaScript添加到页面底部,紧接在结束body标签之前。

运行! ( Run it! )

We are almost at the finish line. Let's try run our setup. We just need to do one tiny thing first. Open up your package.json and let's add a start script.

我们快到终点了。 让我们尝试运行我们的设置。 我们只需要先做一件小事。 打开您的package.json并添加一个启动脚本。

/*
    ./package.json
*/
{
  "name": "hello-world-react",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",

  // add the scripts key to your package.json

  "scripts": {
    "start": "webpack-dev-server"
  },

  "dependencies": {
  ...
  },
  "devDependencies": {
  ...
  }
}

Now we can go to our terminal and run:

现在我们可以转到终端并运行:

> yarn start

Open your browser on http://localhost:8080/. If you check your console you'll see our message "Hey guys and ladies!!". The reason we use localhost:8080 is because webpack-dev-server serves all our files on port 8080. Notice webpack-dev-server is run when we execute our start script.

http://localhost:8080/上打开浏览器。 如果您检查控制台,则会看到我们的消息"Hey guys and ladies!!" 。 我们使用localhost:8080的原因是因为webpack-dev-server在端口8080上提供所有文件。 注意,当我们执行启动脚本时, webpack-dev-server已运行。

Yay, it works. So let's add a simple React Component and see what happens.

是的,它有效。 因此,让我们添加一个简单的React组件,看看会发生什么。

React,React,React ( React, React, React )

I'll do a very basic Hello World React Component. We need to install React dependencies first.

我将做一个非常基本的Hello World React组件。 我们需要先安装React依赖项。

> yarn add react react-dom

Next in the client folder we can add a folder named components and create a file App.jsx.

接下来,在client文件夹中,我们可以添加一个名为components的文件夹,并创建一个App.jsx文件。

> cd client
> mkdir components 
> cd components
> touch App.jsx
> cd ../..

So our file structure now looks like this:

所以我们的文件结构现在看起来像这样:

.
|-- client
     |-- components
         |-- App.jsx
     |-- index.html
     |-- index.js
|-- .babelrc
|-- package.json
|-- webpack.config.js
|-- yarn.lock

While naming component files in React the convention is to use PascalCase thats why our file name starts with a capitalized letter.The extension could be either .jsx or .js, I find it better to explicitly use the .jsx extention on files that I intend to use JSX syntax.

虽然在React中命名组件文件的约定是使用PascalCase这就是为什么我们的文件名以大写字母开头的扩展名可以是.jsx.js ,但我发现最好在要使用的文件上显式使用.jsx扩展名使用JSX语法。

Next let's update the App.jsx file:

接下来,让我们更新App.jsx文件:

/*
    ./client/components/App.jsx
*/
import React from 'react';

export default class App extends React.Component {
  render() {
    return (
     <div style={{textAlign: 'center'}}>
        <h1>Hello World</h1>
      </div>);
  }
}

Lastly, we render our component from our start file, index.js. Let's replace the console.log() with:

最后,我们从起始文件index.js渲染组件。 让我们将console.log()替换为:

/* 
    ./client/index.js
*/
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';

ReactDOM.render(<App />, document.getElementById('root'));

Open bash and start our project. Make sure your terminal reads that you are on the project root folder.

打开bash并开始我们的项目。 确保您的终端读取您在项目根文件夹中。

> yarn start

There we go! Ecstatic that you got all the way to the end!!

好了! 欣喜若狂,您一路走到尽头!!

结论 ( Conclusion )

We now have a working React Environment set-up. I hope that this tutorial shed some light on what the configurations really do and why we need them. Also, if the set-up is a bit too tasking to do on every project you can always fork my repo and have a base to start from.

现在我们有一个可以正常工作的React Environment设置。 我希望本教程可以阐明配置的实际作用以及我们为什么需要它们。 另外,如果每个项目的设置工作都过于繁琐,那么您总是可以派出我的仓库,并有一个基础。

Please feel free to experiment around with different webpack configurations and hit me up with any cool things you've discovered on the comment section.

请随时尝试使用不同的Webpack配置,并用您在评论部分发现的任何很棒的东西来为我服务。

Finally, you can and should try build up a more in depth React Project after the tutorial. Cheers!!

最后,您可以并且应该在本教程之后尝试构建更深入的React Project。 干杯!!

翻译自: https://scotch.io/tutorials/setup-a-react-environment-using-webpack-and-babel

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值