babel和webpack_如何使用Webpack和Babel从头开始设置和部署React应用

babel和webpack

So you’ve been using create-react-app a.k.a CRA for a while now. It’s great and you can get straight to coding. But when do you need to eject from create-react-app and start configuring your own React application? There will be a time when we have to let go of the safety check and start venturing out on our own.

因此,您已经使用create-react-app aka CRA已有一段时间了。 太好了,您可以直接进行编码。 但是何时需要从create-react-app弹出并开始配置自己的React应用程序? 有时候,我们不得不放开安全检查,开始独自冒险。

This guide will cover the most simple React configuration that I’ve personally used for almost all of my React projects. By the end of this tutorial we will have our own personal boilerplate and learn some configurations from it.

本指南将涵盖我亲自用于几乎所有React项目的最简单的React配置。 在本教程结束时,我们将拥有自己的个人样板并从中学习一些配置。

目录 (Table of Contents)
  • Why create your own configuration?

    为什么要创建自己的配置?
  • Configuring webpack 4

    配置Webpack 4
  • Configuring Babel 7

    配置Babel 7
  • Adding Prettier

    增加漂亮
  • Adding source map for better error logs

    添加源映射以获得更好的错误日志
  • Setting up ESLint

    设置ESLint
  • I found errors! What do I do?

    我发现了错误! 我该怎么办?
  • Adding CSS LESS processor

    添加CSS LESS处理器
  • Deploying React app to Netlify

    将React应用程序部署到Netlify
  • Conclusion

    结论

为什么要创建自己的配置? (Why create your own configuration?)

There are certain reasons that make creating your own React configuration make sense. You are likely good with React and you want to learn how to use tools like webpack and Babel on your own. These build tools are powerful, and if you have some extra time, it’s always good to learn about them.

有某些原因使创建自己的React配置变得有意义。 您可能对React很满意,并且想学习如何自己使用webpack和Babel之类的工具。 这些构建工具功能强大,如果您有多余的时间,最好学习一下它们。

Developers are naturally curious people, so if you feel you’d like to know how things work and which part does what, then let me help you with it.

开发人员天生就是好奇的人,因此,如果您觉得自己想知道事情是如何工作的,以及哪个部分在做什么,那么让我来帮助您吧。

Furthermore, hiding React configuration by create-react-app is meant for developers starting to learn React, as configuration should not stand in the way of getting started. But when things get serious, of course you need more tools to integrate in your project. Think about:

此外,通过create-react-app隐藏React配置是为了让开发人员开始学习React,因为配置不应该妨碍入门 。 但是,当事情变得严重时,您当然需要更多工具才能集成到项目中。 想一想:

  • Adding webpack loaders for less, sass

    添加webpack加载程序以减少麻烦
  • Doing server side rendering

    做服务器端渲染
  • Using new ES versions

    使用新的ES版本
  • Adding MobX and Redux

    添加MobX和Redux
  • Making your own configuration just for learning sake

    出于学习目的进行自己的配置

If you look around the Internet, there are some hacks to get around CRA limitations like create-react-app rewired. But really, why not just learn React configuration on your own? I will help you get there. Step by step.

如果您在Internet上四处看看,有一些黑客可以解决CRA的限制,例如create-react-app rewired 。 但是实际上,为什么不只自己学习React配置呢? 我会帮你到达那里。 一步步。

Now that you’re convinced to learn some configuration, let’s start by initializing a React project from scratch.

现在您已经确信要学习一些配置,让我们从头开始初始化React项目。

Open up the command line or Git bash and create a new directory

打开命令行或Git bash并创建一个新目录

mkdir react-config-tutorial && cd react-config-tutorial

Initialize NPM project by running:

通过运行以下命令初始化NPM项目:

npm init -y

Now install react

现在安装react

npm install react react-dom

Also, you can view the source code on GitHub while reading this tutorial for explanations about the settings.

另外,您可以在阅读本教程的同时查看GitHub上的源代码 ,以获取有关设置的说明。

配置Webpack 4 (Configuring webpack 4)

Our first stop will be the webpack. It’s a very popular and powerful tool for configuring not only React, but almost all front-end projects. The core function of webpack is that it takes a bunch of JavaScript files we write in our project and turns them into a single, minified file, so that it will be quick to serve. Starting from webpack 4, we aren’t required to write a configuration file at all to use it, but in this tutorial we will write one so that we can understand it better.

我们的第一站将是webpack。 这是一个非常流行且功能强大的工具,不仅可以配置React,而且还可以配置几乎所有前端项目。 webpack的核心功能是获取我们在项目中编写的一堆JavaScript文件,并将它们转换为单个缩小的文件,以便快速提供服务。 从webpack 4开始,我们完全不需要编写配置文件就可以使用它,但是在本教程中,我们将编写一个配置文件,以便我们可以更好地理解它。

First, let’s do some installation

首先,让我们做一些安装

npm install --save-dev webpack webpack-dev-server webpack-cli

This will install:

这将安装:

  • webpack module — which include all core webpack functionality

    webpack模块 -包括所有核心webpack功能

  • webpack-dev-server — this development server automatically rerun webpack when our file is changed

    webpack-dev- server-更改文件后,此开发服务器会自动重新运行webpack

  • webpack-cli — enable running webpack from the command line

    webpack- cli-启用从命令行运行webpack

Let’s try to run webpack by adding the following script to package.json

让我们尝试通过将以下脚本添加到package.json来运行webpack

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

Now create an index.html file in your root project with the following content:

现在,在根项目中创建具有以下内容的index.html文件:

<!DOCTYPE html>
<html>
 <head>
 <title>My React Configuration Setup</title>
 </head>
 <body>
 <div id="root"></div>
 <script src="./dist/bundle.js"></script>
 </body>
</html>

Create a new directory named src and inside it, create a new index.js file

创建一个名为src的新目录,并在其中创建一个新的index.js文件

mkdir src && cd src && touch index.js

Then write a React component into the file:

然后将一个React组件写入文件中:

import React from "react";
import ReactDOM from "react-dom";
class Welcome extends React.Component {
  render() {
    return <h1>Hello World from React boilerplate</h1>;
  }
}
ReactDOM.render(<Welcome />, document.getElementById("root"));

Run the webpack by using npm run start … And an error will be triggered.

通过使用npm run start来运行webpack…并会触发错误。

You may need an appropriate loader to handle this file type

配置Babel 7 (Configuring Babel 7)

The React component we wrote above used the class syntax, which is a feature of ES6. Webpack needs Babel to process ES6 into ES5 syntaxes in order for this class to work.

我们上面编写的React组件使用了class语法,这是ES6的功能。 Webpack需要Babel将ES6处理为ES5语法,以便此类工作。

Let’s install Babel into our project

让我们将Babel安装到我们的项目中

npm install --save-dev @babel/core @babel/preset-env \@babel/preset-react babel-loader

Why do we need these packages?

我们为什么需要这些软件包?

  • @babel/core is the main dependency that includes babel transform script.

    @ babel / core是包括babel转换脚本的主要依赖项。

  • @babel/preset-env is the default Babel preset used to transform ES6+ into valid ES5 code. Optionally configures browser polyfills automatically.

    @ babel / preset-env是默认的Babel预设,用于将ES6 +转换为有效的ES5代码。 (可选)自动配置浏览器polyfill。

  • @babel/preset-react is used for transforming JSX and React class syntax into valid JavaScript code.

    @ babel / preset-react用于将JSX和React类语法转换为有效JavaScript代码。

  • babel-loader is a webpack loader that hooks Babel into webpack. We will run Babel from webpack with this package.

    babel-loader是一个webpack加载器,可将Babel挂接到webpack中。 我们将使用此软件包从webpack运行Babel。

To hook Babel into our webpack, we need to create a webpack configuration file. Let’s write a webpack.config.js file:

要将Babel挂接到我们的webpack中,我们需要创建一个webpack配置文件。 让我们编写一个webpack.config.js文件:

module.exports = {
  entry: './src/index.js',
  output: {
    path: __dirname + '/dist',
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './dist',
  },
  module: {
    rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: ['babel-loader']
    }
    ]
  },
};

This webpack config is basically saying that the entry point of our application is from index.js, so pull everything that’s needed by that file, then put the output of the bundling process into the dist directory, named bundle.js. Oh, if we’re running on webpack-dev-server, then tell the server to serve content from contentBase config, which is the same directory this config is in. For all .js or .jsx files, use babel-loader to transpile all of them.

这个webpack配置基本上是说我们应用程序的entry点来自index.js,因此请提取该文件所需的所有内容,然后将捆绑过程的output放到名为bundle.jsdist目录中。 哦,如果我们在webpack-dev-server上运行,则告诉服务器从contentBase配置(该配置所在的目录)中提供内容。对于所有.js或.jsx文件,请使用babel-loader进行转换他们全部。

In order to use Babel presets, create a new .babelrc file

为了使用Babel预设,请创建一个新的.babelrc文件

touch .babelrc

Write the following content:

编写以下内容:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

Now run npm run start again. This time it will work.

现在运行npm run start 。 这次它将起作用。

增加漂亮 (Adding Prettier)

To further speed up development, let’s make our code formatter using Prettier. Install the dependency locally and use the — save-exact argument since Prettier introduces stylistic changes in patch releases.

为了进一步加快开发速度,让我们使用Prettier制作代码格式化程序。 由于Prettier在修补程序版本中引入了样式更改,因此请在本地安装依赖项并使用-save-exact参数。

npm install --save-dev --save-exact prettier

Now we need to write the .prettierrc configuration file:

现在我们需要编写.prettierrc配置文件:

{
 "semi": true,
 "singleQuote": true,
 "trailingComma": "es5"
}

The rules means that we want to add semicolon for the end of every statement, use a single quote whenever appropriate and put trailing commas for multi-line ES5 code like objects or arrays.

这些规则意味着我们要在每个语句的末尾添加分号,在适当的时候使用单引号,并在多行ES5代码(例如对象或数组)中添加尾随逗号。

You can run Prettier from the command line with:

您可以使用以下命令从命令行运行Prettier:

npx prettier --write "src/**/*.js"

Or add a new script to our package.json file:

或将新脚本添加到我们的package.json文件中:

"scripts": {
 "test": "echo \"Error: no test specified\" && exit 1",
 "start": "webpack-dev-server --mode development",
 "format": "prettier --write \"src/**/*.js\""
},

Now we can run Prettier using npm run format.

现在我们可以使用npm run format运行Prettier了。

Additionally, if you’re using VSCode for development, you can install the Prettier extension and run it every time you save your changes by adding this setting:

此外,如果您使用VSCode进行开发,则可以通过添加以下设置来安装Prettier 扩展并在每次保存更改时运行它:

"editor.formatOnSave": true

添加源映射以获得更好的错误日志 (Adding source map for better error logs)

Since webpack bundles the code, source maps are mandatory to get a reference to the original file that raised an error. For example, if you bundle three source files (a.js, b.js, and c.js) into one bundle (bundler.js) and one of the source files contains an error, the stack trace will simply point to bundle.js. This is problematic as you probably want to know exactly if it’s the a, b, or c file that is causing an error.

由于webpack捆绑了代码,因此必须使用源映射来获取对引发错误的原始文件的引用。 例如,如果将三个源文件( a.jsb.jsc.js )捆绑到一个捆绑包( bundler.js )中,并且其中一个源文件包含错误,则堆栈跟踪将仅指向bundle.js 。 这很成问题,因为您可能想确切地知道是a,b还是c文件导致了错误。

You can tell webpack to generate source maps using the devtool property of the configuration:

您可以告诉webpack使用配置的devtool属性生成源映射:

module.exports = {
  devtool: 'inline-source-map',
  // … the rest of the config
};

Although it will cause a slower build, it has no effect on production. Sourcemaps are only downloaded if you open the browser DevTools.

尽管它将导致构建速度变慢,但对生产没有影响。 仅在打开浏览器DevTools时才下载源地图

设置ESLint (Setting up ESLint)

Linter is a program that checks our code for any error or warning that can cause bugs. JavaScript’s linter, ESLint, is a very flexible linting program that can be configured in many ways.

Linter是一个程序,用于检查我们的代码是否存在任何可能导致错误的错误或警告。 JavaScript的linter ESLint是一种非常灵活的linting程序,可以通过多种方式进行配置。

But before we get ahead, let’s install ESLint into our project:

但是在开始之前,让我们将ESLint安装到我们的项目中:

npm --save-dev install eslint eslint-loader babel-eslint eslint-config-react eslint-plugin-react
  • eslint is the core dependency for all functionalities, while eslint-loader enables us to hook eslint into webpack. Now since React used ES6+ syntax, we will add babel-eslint — a parser that enables eslint to lint all valid ES6+ codes.

    eslint是所有功能的核心依赖项,而eslint-loader使我们能够将eslint挂钩到webpack中。 现在,由于React使用ES6 +语法,我们将添加babel-eslint —一种解析器,使eslint可以整理所有有效的ES6 +代码。

  • eslint-config-react and eslint-plugin-react are both used to enable ESLint to use pre-made rules.

    eslint-config-reacteslint-plugin-react都用于使ESLint使用预设规则。

Since we already have webpack, we only have to modify the config slightly:

既然我们已经有了webpack,我们只需要稍微修改一下配置即可:

module.exports = {
  // modify the module
  module: {
    rules: [{
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: ['babel-loader', 'eslint-loader'] // include eslint-loader
    }]
  },
};

Then create an eslint config file named .eslintrc with this content:

然后使用以下内容创建一个名为.eslintrc的eslint配置文件:

{
  "parser": "babel-eslint",
  "extends": "react",
  "env": {
    "browser": true,
    "node": true
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}

The config is basically saying, “Hey ESLint, please parse the code using babel-eslint before you check it, and when you’re checking it, please check if all the rules from our React rules config is passed. Take global variables from the environment of browser and node. Oh, and if it’s React code, take the version from the module itself. That way the user won’t have to specify the version manually.

配置基本上是说: “嗨,ESLint,请在检查代码之前使用babel-eslint解析代码,然后在检查代码时,请检查是否通过了React规则配置中的所有规则。 从浏览器和节点的环境中获取全局变量。 哦,如果是React代码,请从模块本身获取版本。 这样,用户将不必手动指定版本。

Rather than specifying our own rules manually, we simply extend react rules which were made available by eslint-config-react and eslint-plugin-react.

eslint-config-react手动指定我们自己的规则,我们只需扩展eslint-config-reacteslint-plugin-react可用的react规则。

我发现了错误! 我该怎么办? (I found errors! What do I do?)

Unfortunately the only way to really figure out how to fix ESLint errors is by looking at the documentation for rules. There’s a quick way to fix ESLint errors by using eslint--fix, and it’s actually good for a quick fix. Let’s add a script on our package.json file:

不幸的是,真正弄清楚ESLint错误的唯一方法是查看规则文档。 有一种使用eslint--fix修复ESLint错误的快速方法,实际上对快速修复很有用。 让我们在package.json文件上添加一个脚本:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "webpack-dev-server --mode development",
  "format": "prettier --write \"src/**/*.js\"",
  "eslint-fix": “eslint --fix \"src/**/*.js\"", // the eslint script
  "build": "webpack --mode production"
},

Then run it with npm run eslint-fix. Don’t worry if you’re still fuzzy about ESLint for now. You will learn more about ESLint as you use it.

然后使用npm run eslint-fix运行它。 如果您现在仍然对ESLint感到困惑,请不要担心。 使用它时,您将了解有关ESLint的更多信息。

添加CSS LESS处理器 (Adding CSS LESS processor)

In order to add the LESS processor into our React application, we will require both less and loader packages from webpack:

为了将LESS处理器添加到我们的React应用程序中,我们将需要webpack的less和loader软件包:

npm install --save-dev less less-loader css-loader style-loader

less-loader will compile our less file into css, while css-loader will resolve css syntax like import or url(). The style-loader will get our compiled css and load it up into <style> tag in our bundle. This is great for development because it lets us update our style on the fly, without needing to refresh the browser.

less-loader将把less文件编译成css,而css-loader将解析css语法,例如importurl()style-loader将获取我们已编译的css,并将其加载到我们包中的<sty le>标记中。 这对开发非常有用,因为它使我们可以即时更新样式,而无需刷新浏览器。

Now let’s add some css files to create a new style directory in src/style

现在让我们添加一些css文件以在src/style创建一个新的样式目录

cd src && mkdir style && touch header.less && touch main.less

header.less content:

header.less内容:

.header {
  background-color: #3d3d;
}

main.less content:

main.less内容:

@import "header.less";
@color: #f5adad;
body {
  background-color: @color;
}

Now import our main.less file from index.js:

现在从index.js导入我们的main.less文件:

import "./style/main.less";

Then update our webpack configuration module property:

然后更新我们的webpack配置module属性:

module: {
  rules: [{
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    use: ['babel-loader', 'eslint-loader']
  },
  {
    test: /\.less$/,
    use: [
      'style-loader',
      'css-loader',
      'less-loader',
    ],
  },
 ]
},

Run the start script and we’re good to go!

运行启动脚本,我们很好!

将React应用程序部署到Netlify (Deploying React app to Netlify)

All applications need to be deployed for the last step, and for React applications, deployment is very easy.

最后一步需要部署所有应用程序,而对于React应用程序,部署非常容易。

First, let’s change the build output and development contentBase from dist to build in our Webpack config.

首先,让我们来构建输出和发展变化contentBasedistbuild我们的WebPack配置。

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'build'), // change this
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: "./build",
  },
//…

Now let’s install a new Webpack plugin named HtmlWebpackPlugin

现在,让我们安装一个名为HtmlWebpackPlugin的新Webpack插件

npm install html-webpack-plugin -D

This plugin will generate index.html file in the same directory where our bundle.js is created by Webpack. In this case, the build directory.

该插件将在bundle.js创建bundle.js的同一目录中生成index.html文件。 在这种情况下, build目录。

Why do we need this plugin? Because Netlify requires a single directory to be made the root directory, so we can’t use index.html in our root directory using Netlify. You need to update your webpack config to look like this:

为什么我们需要这个插件? 由于Netlify需要一个目录来进行的根目录下,所以我们不能使用index.html使用Netlify在我们的根目录下。 您需要更新您的webpack配置,如下所示:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: //…
  output: {
    //…
  },
  devServer: {
    contentBase: "./build",
  },
  module: {
    //…
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve('./index.html'),
    }),
  ]
};

And please remove the script tag from your index.html:

并且请从您的index.html删除script标签:

<!DOCTYPE html><html>  <head>    <title>My React Configuration Setup</title>  </head>  <body>    <div id="root"></div>  </body></html><!DOCTYPE html>
<html>
  <head>
    <title>My React Configuration Setup</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Now you can test the config with npm run build command. Once it’s done, push your boilerplate into a GitHub repo. It’s time to deploy our application!

现在,您可以使用npm run build命令测试配置。 完成后,将样板放入GitHub存储库中。 现在该部署我们的应用程序了!

Now let’s register a Netlify account. If you haven’t heard of Netlify before, it’s an amazing static site hosting that provides all the tools you need to deploy a static site for free. What’s a static site? It’s a website created from a collection of static HTML pages, without any backend. Our React boilerplate as it is now counts as a static site, because we have no backend configured and its just HTML and JavaScript.

现在让我们注册一个Netlify帐户。 如果您以前从未听说过Netlify,那么这是一个了不起的静态站点托管,它提供了免费部署静态站点所需的所有工具。 什么是静态网站? 这是一个由静态HTML页面集合创建的网站,没有任何后端。 我们的React样板现在被视为静态站点,因为我们没有配置后端,而只有HTML和JavaScript。

After sign up, select new site from Git and Choose GitHub as your Git provider:

注册后,从Git中选择新站点,然后选择GitHub作为您的Git提供者:

You need to grant permissions for Netlify, and then select your React boilerplate repo.

您需要授予Netlify权限,然后选择您的React样板存储库。

Now you need to enter the build command and publishing directory. As you can see, this is why we need HtmlWebpackPlugin, because we need to serve everything from one directory only. Rather than manually updating our root index.html file for changes, we just generate it using the plugin.

现在,您需要输入build命令并发布目录。 如您所见,这就是为什么我们需要HtmlWebpackPlugin的原因,因为我们只需要提供一个目录中的所有内容。 与其手动更新我们的根index.html文件进行更改,不如使用插件来生成它。

Make sure you have the same command as the screenshot above, or your app might not run.

确保您具有与上述屏幕截图相同的命令,否则您的应用程序可能无法运行。

Once the deploys status turns to published (number 2 above), you can go to the random site name Netlify has assigned for your application (number 1).

一旦部署状态变为published (上面的编号2),您可以转到Netlify为您的应用程序分配的随机站点名称(编号1)。

Your React application is deployed. Awesome!

您的React应用程序已部署。 太棒了!

结论 (Conclusion)

You’ve just created your very own React project boilerplate and deploy it live to Netlify. Congratulations! Granted, I didn’t go very deep on webpack configurations, because this boilerplate is meant to be a generic starter. In some cases where we need advanced features like server side rendering, we need to tweak the configuration again.

您刚刚创建了自己的React项目样板并将其实时部署到Netlify。 恭喜你! 诚然,我对Webpack的配置没有深入了解,因为这个样板本来是一个通用的入门书。 在某些情况下,我们需要服务器端渲染之类的高级功能,我们需要再次调整配置。

But relax! You’ve come this far, which means you already understand what webpack, Babel, Prettier and ESLint do. Webpack has many powerful loaders that can help you with many cases you’ll frequently counter when building a web application.

但是放松! 您已经走了这么远,这意味着您已经了解webpack,Babel,Prettier和ESLint的功能。 Webpack具有许多强大的加载程序,可以帮助您处理在构建Web应用程序时经常遇到的许多情况。

Also, I’m currently writing a book to help software developers learn about React, so you might wanna check it out!

另外,我目前正在写一本书,以帮助软件开发人员了解React,所以您可能想看看

You can read more of my React tutorials at sebhastian.com.

您可以在sebhastian.com上阅读更多我的React教程。

翻译自: https://www.freecodecamp.org/news/how-to-set-up-deploy-your-react-app-from-scratch-using-webpack-and-babel-a669891033d4/

babel和webpack

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值