惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
V
Visual Studio Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
Apple Machine Learning Research
Apple Machine Learning Research
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
Recent Announcements
Recent Announcements
V
V2EX
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
V
Vulnerabilities – Threatpost
C
Check Point Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
AI
AI
宝玉的分享
宝玉的分享
P
Proofpoint News Feed
量子位
Attack and Defense Labs
Attack and Defense Labs
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Privacy International News Feed
Google DeepMind News
Google DeepMind News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
CERT Recently Published Vulnerability Notes
腾讯CDC
Latest news
Latest news
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
G
GRAHAM CLULEY
Blog — PlanetScale
Blog — PlanetScale
博客园_首页
美团技术团队
The Cloudflare Blog
T
Tenable Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
J
Java Code Geeks
SecWiki News
SecWiki News
Webroot Blog
Webroot Blog
N
News | PayPal Newsroom
博客园 - 叶小钗
博客园 - Franky

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
How To Setup Your Local React Playground
Dmitri Pavlutin · 2020-02-11 · via Dmitri Pavlutin Blog

It's natural to learn new things playing and having fun. Children, kittens, puppies explore the world playing.

The same approach is useful in programming. If you'd like to try new React features, explore an idea, implement a simple demo, then you need a playground.

In this post, I will show you how to setup a React playground with almost zero configuration in 3 easy steps (using parcel bundler).

1. Step 1: install parcel

The first step is one command: install globally the parcel bundler (I'm using the version 1.12.4).

Run the command to install the parcel bundler using npm:


npm install -g parcel-bundler


or if you use yarn:


yarn global add parcel-bundler


The next step is to create the source files.

2. Step 2: create source files

You need to create the playground directory and place there 2 files: the HTML code and the React code.

I will name the directory react-playground, but you can choose your own. Let's create the new directory and enter into it:


mkdir react-playground && cd react-playground


Now, being inside the react-playground directory, let's create 2 source files.

The first file index.jsx contains the React code:


// index.jsx

import React from 'react';

import ReactDOM from 'react-dom';

function App() {

return <h1>Your React Playground is ready!</h1>;

}

ReactDOM.render(

<App />,

document.getElementById('root')

);


The second file index.html contains the HTML code (the script tag links to ./index.jsx file):


<!-- index.html -->

<html>

<body>

<div id="root"></div>

<script src="./index.jsx"></script>

</body>

</html>


After creating the directory and files, your playground has the following items:


react-playground

├── index.html

└── index.jsx


3. Step 3: run parcel

After the files index.html and index.jsx have been created in your playground's directory, simply run the build command:

What a bit until parcel automatically installs the dependencies (react, react-dom, etc) and builds the playground. Finally, when the building has been completed, your playground is available at http://localhost:1234. Have fun!

React Playground Ready

You can start making changes to your playground right away. As soon as you change the source files, parcel automatically rebuilds the application, then updates the web page. Pretty cool!

If your playground needs more libraries, you don't have to install them manually. Simply require the needed library using import syntax, and parcel automatically installs the required dependencies.

Note that parcel installs the latest stable dependencies at the time of running the build command. But you can customize the dependencies versions.

4. Customizations

Let's see the common customizations you'd possibly need.

4.1 Add CSS

Adding styles to your local playground application is easy.

First, create the file styles.css in your playground project directory:


/* styles.css */

h1 {

font-style: italic;

}


Secondly, update the index.html to link to the new external CSS file:


<!-- index.html -->

<html>

<head>

<link rel="stylesheet" href="./styles.css">

</head>

<body>

<div id="root"></div>

<script src="./index.jsx"></script>

</body>

</html>


Without any further configuration, parcel picks the CSS file and applies it. Any change to the stylesheets triggers a rebuild and web page update. Great.

React Playground With CSS

4.2 Specific versions of dependencies

By default, parcel installs the latest stable dependencies. But you can easily customize the dependencies versions.

After the first build, parcel generates a package.json file in the playground directory:


react-playground

├── index.html

├── index.jsx

└── package.json


To install a specific dependency version, for example of React and React DOM, simply update package.json:


// package.json

{

"dependencies": {

"react": "16.12.0",

"react-dom": "16.12.0"

}

}


4.3 TypeScript support

Rename the React source file to index.tsx (.tsx extension instead of .jsx), and parcel automatically enables the support of TypeScript.

Create a file index.tsx having some TypeScript code:


// index.tsx

import * as React from 'react';

import * as ReactDOM from 'react-dom';

function App(): JSX.Element {

return <h1>Your React Playground is ready!</h1>;

}

ReactDOM.render(

<App />,

document.getElementById('root')

);


Then update the HTML file so that the script tag to point to index.tsx file:


<!-- index.html -->

<html>

<body>

<div id="root"></div>

<script src="./index.tsx"></script>

</body>

</html>


Finally, install the React types modules:


npm install --save-dev @types/react @types/react-dom


Now your playground has TypeScript support. The editor should start type checking.

5. Conclusion

Playgrounds are a great way to play with the new features of React, test ideas, wire up a quick demo. If you prefer to have all your source code locally, then using parcel is a good start.

To setup a local React playground 3 easy steps are needed. Install parcel bundler globally, create your project directory with 2 source files: the HTML and React source files. Finally, just run the parcel build command. The playground is ready!

If for some reason you don't like parcel, an alternative is the known create-react-app. If you don't like local playgrounds, I have had a good experience with codesandbox.io.

Happy playing!