react项目设置全局变量_如何使用宗地设置React项目

本文介绍了如何使用ParcelJS快速设置React应用。ParcelJS是一个零配置的Web应用打包工具,提供了快速打包、自动转换、代码拆分和热模块替换等功能。教程详细讲解了从创建工作目录、安装依赖、配置Babel到构建React组件的步骤,还包括Parcel支持SCSS和图片导入的特性,以及如何为生产环境做准备。
摘要由CSDN通过智能技术生成

react项目设置全局变量

介绍 (Introduction)

When it comes to web application bundling, ParcelJS is a relatively new bundler. Parcel describes itself as a blazing fast, zero-configuration web application bundler.

当涉及到Web应用程序捆绑时, ParcelJS是一个相对较新的捆绑器。 Parcel将自己描述为一个快速,零配置的Web应用程序捆绑包。

Parcel is based on the premise that building apps with JavaScript bundlers could be easier. Webpack is arguably the most popular bundler out there right now, it’s an awesome tool that gives you the power of configurability but sometimes all you need is a minimal tool that helps you get started as soon as possible.

Parcel的前提是,使用JavaScript捆绑器构建应用可能会更容易。 Webpack可以说是目前最受欢迎的捆绑器,它是一个了不起的工具,可为您提供可配置性,但有时您所需要的只是一个最小的工具,可帮助您尽快上手。

This is where Parcel comes in. It touts itself as a fast bundle tool with zero configuration—all you need to is just point it at the entry point of your application. Parcel also offers the following features:

这就是Parcel的用处。它自称为具有零配置的快速捆绑工具-您所要做的只是将其指向应用程序的入口点。 包裹还提供以下功能:

  • Fast bundle times - Parcel has a considerably faster time than other bundling tools out there. Below is a screenshot of the Parcel page on Github.

    Screenshot of Parcel benchmarks

    捆绑时间短-与其他捆绑工具相比,Parcel的时间要快得多。 以下是Github上包裹页面的屏幕截图。

  • Assets Bundling - Parcel has out of the box support for JS, CSS, HTML, file assets.

    资产捆绑-包裹具有对JS,CSS,HTML,文件资产的开箱即用支持。
  • Automatic transforms - All your code are automatically transformed using Babel, PostCSS, and PostHTML.

    自动转换-使用Babel,PostCSS和PostHTML自动转换所有代码。
  • Code Splitting - Parcel allows you to split your output bundle by using the dynamic import() syntax.

    代码拆分-使用Parcel,您可以使用动态import()语法拆分输出包。
  • Hot module replacement (HMR) - Parcel automatically updates modules in the browser as you make changes during development, no configuration needed.

    热模块更换(HMR)-在开发过程中进行更改时,Parcel会自动更新浏览器中的模块,无需进行配置。
  • Error Logging - Parcel prints syntax highlighted code frames when it encounters errors to help you pinpoint the problem.

    错误记录-包裹遇到错误时,Parcel会打印语法突出显示的代码帧,以帮助您查明问题。

One other thing to note about Parcel is that it allows developers to use an index.html file as an entry point as opposed to JS modules.

关于Parcel的另一件事要注意的是,它允许开发人员使用index.html文件作为入口点,而不是JS模块。

In this tutorial, you will set up a React web app with Parcel.

在本教程中,您将使用Parcel设置一个React Web应用程序。

第1步-包裹入门 (Step 1 — Getting Started With Parcel)

To get started, create a new working directory and install Parcel by running the command below in your terminal:

首先,创建一个新的工作目录并通过在终端中运行以下命令来安装Parcel:

  • npm install -g parcel-bundler

    npm install -g包裹捆绑程序

The next thing to do is create a package.json file in your directory. You can do this by running the command below:

下一步要做的是在目录中创建一个package.json文件。 您可以通过运行以下命令来执行此操作:

  • npm init -y

    npm初始化-y

That generates a working package.json for you.

会为您生成一个有效的package.json

Parcel can take any type of file as its entry point, but an HTML or JavaScript file is a good place to start. If you link your main JavaScript file in the HTML using a relative path, Parcel will also process it for you. Create the index.html and index.js files and add the following content to them:

包裹可以使用任何类型的文件作为其入口点,但是HTML或JavaScript文件是一个很好的起点。 如果您使用相对路径在HTML中链接主JavaScript文件,Parcel也会为您处理该文件。 创建index.htmlindex.js文件,并向其中添加以下内容:

index.html
index.html
<html>
<body>
  <script src="./index.js"></script>
</body>
</html>
index.js
index.js
console.log("hello world");

Now that the files are created, you’re ready to run the app. Parcel comes with a development server built in which will automatically rebuild your app as you change files and supports hot module replacement for fast development. To run the app, run the terminal command below:

现在已经创建了文件,您可以运行该应用程序了。 Parcel带有内置的开发服务器,当您更改文件时,该服务器将自动重建您的应用程序,并支持热模块更换以实现快速开发。 要运行该应用程序,请运行以下终端命令:

  • parcel index.html

    包裹index.html

You can now open http://localhost:1234/ in your browser and check the console for the output in the console.

Console displaying "hello world" text

现在,您可以在浏览器中打开http://localhost:1234/ ,并在控制台中检查控制台中的输出。

第2步-使用Parcel和React设置项目 (Step 2 — Setting up a Project with Parcel and React)

Next you will set up a React project with Parcel. Before you continue, you’ll need to install some dependencies:

接下来,您将使用Parcel设置一个React项目。 在继续之前,您需要安装一些依赖项:

  • npm i react

    我React
  • npm i react-dom

    npm我React

The dependencies above will install React and react-dom in your application. Since React is written in ES6, we’ll need a way to transform the code. Parcel does that for you with no need for configurations. All you have to do is install the presets and Parcel does the heavy lifting for you.

上面的依赖项将在您的应用程序中安装React和react-dom 。 由于React是用ES6编写的,因此我们需要一种方法来转换代码。 包裹无需您配置即可为您完成。 您所要做的就是安装预设,然后包裹将为您完成繁重的工作。

  • npm i babel-preset-env babel-preset-react --save-dev

    npm我babel预设环境env babel预设React--save-dev

Once that’s done, create a .babelrc file and edit it with the following:

完成后,创建一个.babelrc文件,并使用以下内容对其进行编辑:

.babelrc
.babelrc
{
  "presets": ["env", "react"]
}

Now Babel is configured to transform ES6/ES7 JavaScript into a meaningful JavaScript bundle for browsers.

现在,Babel已配置为将ES6 / ES7 JavaScript转换为对浏览器有意义JavaScript包。

Now you can begin to create the React app and its components. Open up the index.html file and replace it with the code below.

现在您可以开始创建React应用及其组件。 打开index.html文件,并将其替换为下面的代码。

index.html
index.html
<!DOCTYPE html>
<html>
<head>
    <title>React starter app</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">
</head>
<body>
<div id="app"></div>
<script src="./src/index.js"></script>
</body>
</html>

Next up, create a folder titled src and in it create an index.js file and edit it with the following:

接下来,创建一个名为src的文件夹,并在其中创建index.js文件,并使用以下内容进行编辑:

src/index.js
src / index.js
import React from "react";
import ReactDOM from "react-dom";
import Header from './components/Header'

class HelloMessage extends React.Component {
    render() {
        return <div>
            <Header/>
            <div className="container">
                <h1>Hello {this.props.name}</h1>
            </div>
        </div>
    }
}

let App = document.getElementById("app");

ReactDOM.render(<HelloMessage name="Yomi" />, App);

This is a basic React starting app. The HelloMessage component will be rendered in the index.html file in the div with an ID of app.

这是一个基本的React启动应用程序。 HelloMessage组件将在divindex.html文件中呈现,其ID为app

Next, create a Header component. Create a component folder and in it, create a JS file titled Header.js and edit it with the code below.

接下来,创建一个Header组件。 创建一个component文件夹,并在其中创建一个名为Header.js的JS文件,并使用以下代码对其进行编辑。

component/Header.js
组件/Header.js
import React from 'react'
import ParcelLogo from "../img/parcel-logo.svg";

const Header = () => (
    <header>
        <nav className="navbar" role="navigation" aria-label="main navigation">
            <div className="navbar-brand">
                <a className="navbar-item" href="/">
                    <img width="120" src={ParcelLogo} alt=""/>
                </a>
            </div>
        </nav>
    </header>
)

export default Header

Parcel also supports the import of assets like images. One more thing to note is that, Parcel also ships with SCSS support. To use it, install node-sass:

包裹还支持图像等资产的导入。 需要注意的另一件事是,Parcel还附带了SCSS支持。 要使用它,请安装node-sass

  • npm i node-sass

    npm我节点萨斯

Once you have node-sass installed, you can import SCSS files from JavaScript files. In your index.js file, add the line of code below to the top of the file to import an SCSS file:

一旦安装了node-sass ,就可以从JavaScript文件导入SCSS文件。 在index.js文件中,将以下代码行添加到文件顶部以导入SCSS文件:

index.js
index.js
import './scss/app.scss'
...

Let’s also create the app.scss file. Create a folder titled scss and create a file titled app.scss and edit it with the following:

我们还要创建app.scss文件。 创建一个名为scss的文件夹,并创建一个名为app.scss的文件,并使用以下命令对其进行编辑:

scss/app.scss
scss / app.scss
body {
  background-color: #fefefe;
  text-align: center;
  .navbar {
    background: #21374B;
    color: #E7DACB;
    height: 50px;
  }
  h1 {
    font-size: 40px;
    margin-top: 30px;
  }
}

Now that you’re done setting up the React app, run it and see if it works. To do that, you’ll need to start a dev server and configure the package.json. Add the line of code below to the package.json file:

既然您已经完成了React应用的设置,请运行它并查看它是否有效。 为此,您需要启动开发服务器并配置package.json 。 将以下代码行添加到package.json文件:

package.json
package.json
"scripts": {
    "start": "parcel index.html"
  },

This means that whenever you run the npm start command, you are telling Parcel to start a development server using the index.html file as a entry file. Run the npm start command and you can now view the React app at http://localhost:1234 with support for hot module reloading.

这意味着无论何时运行npm start命令,您都在告诉Parcel使用index.html文件作为入口文件来启动开发服务器。 运行npm start命令,您现在可以在http://localhost:1234上查看支持热模块重新加载的React应用程序。

第3步-生产建设 (Step 3 — Building for Production)

To prepare your app for production with Parcel, you need to run the parcel build index.html command. Add that to the scripts object in the package.json file.

要准备使用Parcel进行生产的应用程序,您需要运行parcel build index.html命令。 将其添加到package.json文件中的scripts对象。

package.json
package.json
"scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html"
  },

Once you run the npm run build command, Parcel disables watch mode and hot module replacement so it will only build once. It also enables the minifier for all output bundles to reduce file size. The build command also enables production mode which also sets the NODE_ENV=production environment variable.

一旦运行npm run build命令,Parcel将禁用监视模式和热模块替换,因此它将仅生成一次。 它还可以使所有输出包的压缩程序减小文件大小。 build命令还启用生产模式,该模式还设置了NODE_ENV=production环境变量。

Parcel also gives you some options in which you can use to choose how your app is prepared for production mode.

Parcel还为您提供了一些选项,您可以在其中使用这些选项来选择如何为生产模式准备应用程序。

If you’d prefer another directory for Parcel to put the production files in (dist is the default directory), you can specify that by appending --out-dir directory-name at the end of the build key in package.json so it looks like this:

如果您希望Parcel使用另一个目录将生产文件放入( dist是默认目录),则可以通过在package.jsonbuild密钥末尾附加--out-dir directory-name来指定该--out-dir directory-name ,看起来像这样:

package.json
package.json
"scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html --out-dir directory-name"
  },

If you’d like to disable minification which is the default setting, you can do that by appending --no-minify at the end of the build key in package.json so it looks like this:

如果您想禁用最小化(这是默认设置),则可以通过在package.jsonbuild键末尾附加--no-minify来做到这一点,如下所示:

package.json
package.json
"scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html --no-minify"
  },

If you’d like to disable filesystem caching, you can do that by appending --no-cache at the end of the build key in package.json so it looks like this:

如果您想禁用文件系统缓存,可以通过在package.jsonbuild键末尾附加--no-cache来做到这一点,如下所示:

package.json
package.json
"scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html --no-cache"
  },

You can read more about the different options here.

您可以在此处阅读更多有关不同选项的信息

结论 (Conclusion)

In this tutorial, you bundled a web app with Parcel. Parcel is still relatively new and its support keeps growing in numbers every day. Its use case might be different from Webpack, but it’s a bundle tool that can be considered in your everyday web development.

在本教程中,您将Web应用程序与Parcel捆绑在一起。 包裹仍然相对较新,其支持每天都在增长。 它的用例可能与Webpack不同,但是它是一个捆绑工具,可以在您的日常Web开发中考虑。

You can check out the Parcel repo here to see issues and submit PRs.

您可以在此处签出包裹回购以查看问题并提交PR。

The codebase for this tutorial can be found on GitHub.

可以在GitHub上找到本教程的代码库。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-react-project-with-parcel

react项目设置全局变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值