日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用 create-react-app 构建 react应用程序

發(fā)布時間:2024/4/14 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用 create-react-app 构建 react应用程序 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>

本文主要是對SPA搭建的實踐過程講解,在對react、redux、react-router有了初步了解后,來運用這些技術(shù)構(gòu)建一個簡單的單頁應(yīng)用。這個應(yīng)用包括了側(cè)邊導(dǎo)航欄與主體內(nèi)容區(qū)域。下面簡單羅列了將會用到的一些框架與工具。

  • create-react-app:腳手架
  • react:負(fù)責(zé)頁面組件構(gòu)建
  • react-router:負(fù)責(zé)單頁應(yīng)用路由部分的控制
  • redux:負(fù)責(zé)管理整個應(yīng)用的數(shù)據(jù)流
  • react-redux:將react與redux這兩部分相結(jié)合
  • redux-thunk:redux的一個中間件。可以使action creator返回一個function(而不僅僅是object),并且使得dispatch方法可以接收一個function作為參數(shù),通過這種改造使得action支持異步(或延遲)操作
  • redux-actions:針對redux的一個FSA工具箱,可以相應(yīng)簡化與標(biāo)準(zhǔn)化action與reducer部分

create-react-app 是一個全局的命令行工具用來創(chuàng)建一個新的項目

react-scripts 是一個生成的項目所需要的開發(fā)依賴

??
? ? ? 一般我們開始創(chuàng)建react web應(yīng)用程序的時候,要自己通過 npm 或者 yarn 安裝項目的全部依賴,再寫webpack.config.js,一系列復(fù)雜的配置,搭建好開發(fā)環(huán)境后寫src源代碼。
現(xiàn)在 如果你正在搭建react運行環(huán)境,使用 create-react-app 去自動構(gòu)建你的app程序。你的項目所在的文件夾下是沒有配置文件。react-scripts 是唯一的 額外的 構(gòu)建依賴在你的package.json中,你的運行環(huán)境將有每一個你需要用來構(gòu)建一個現(xiàn)代React app應(yīng)用程序。你需要的依賴,和在配置文件中編寫的配置代碼,react-scripts 都幫你寫了,比如:react-scripts幫你自動下載需要的 webpack-dev-server 依賴,然后react-scripts自己寫了一個nodejs服務(wù)端的腳本代碼 start.js來 實例化 WebpackDevServer ,并且運行啟動了一個使用 express 的Http服務(wù)器,現(xiàn)在你只需要專心寫src源代碼就可以了。省去了很多精力,最適合快速上手一個demo了。

react-scripts有以下支持,都幫你配置好了:
React, JSX, ES6, and Flow syntax support.
Language extras beyond ES6 like the object spread operator.
Import CSS and image files directly from JavaScript.
Autoprefixed CSS, so you don’t need -webkit or other prefixes.
A build script to bundle JS, CSS, and images for production, with sourcemaps.
A dev server that lints for common errors.

使用create-react-app腳手架

create-react-app是Facebook官方出品的腳手架。有了它,你只需要一行指令即可跳過webpack繁瑣的配置、npm繁多的引入等過程,迅速構(gòu)建react項目。

安裝

npm install -g create-react-app

創(chuàng)建一個應(yīng)用程序?

create-react-app my-app cd my-app

生成的目錄結(jié)構(gòu)

my-app/ README.md node_modules/ package.json .gitignore public/ favicon.ico index.html src/ App.css App.js App.test.js index.css index.js logo.svg

運行應(yīng)用程序

npm run start

在瀏覽器中打開

http://localhost:3000

現(xiàn)在我們看 my-app文件夾下的public/index.html 和src/index.js的源碼,我們可以在這里編寫項目代碼,但是注意 public/index.html 是啟動http服務(wù)器的首頁,src/index.js是編譯的入口文件,只能叫index這個名字,改別的名字不行。
打開 http://localhost:3000/index.html 首頁,f12查看 網(wǎng)頁源碼,你會看到?

<script type="text/javascript" src="/static/js/bundle.js"></script>

/static/js/bundle.js
在你的項目my-app你是看不到這個文件路徑的,你也沒有寫配置文件webpack.config.js,
http服務(wù)器配置,自動代開瀏覽器窗口,react,es6語法編譯,babel-core,webpack,等等這些 你都沒下載,配置。
這些活,react-scripts 都幫你做了。

回顧?
npm run start
我們 一開始這么啟動服務(wù) 運行項目
打開你的my-app\package.json

"scripts": { "start": "react-scripts start", ... }

所以執(zhí)行的是 react-scripts start?
打開你的my-app\node_modules\react-scripts這個文件夾下的bin文件夾下的react-scripts.js文件

#!/usr/bin/env node var spawn = require('cross-spawn'); var script = process.argv[2]; var args = process.argv.slice(3); switch (script) { case 'build': case 'eject': case 'start': case 'test': var result = spawn.sync( 'node', [require.resolve('../scripts/' + script)].concat(args), .......

上面代碼中 ?script 的變量值是 start
所以執(zhí)行 my-app\node_modules\react-scripts\scripts 文件夾下的 ?start.js 文件代碼節(jié)選重點如下

var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); // 啟動http服務(wù)器 var paths = require('../config/paths'); //要編譯的文件路徑與生成路徑等 var config = require('../config/webpack.config.dev'); var DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; //這就是為什么 端口號 不是8080 而是 3000 的原因,在這里可以改成8080,重新npm run start 生效 detect(DEFAULT_PORT).then(port => { if (port === DEFAULT_PORT) { run(port); //這里開始運行 return; } ...... function run(port) { // 這里可以設(shè)置 http協(xié)議, 或者可以在 npm run start 之前 cmd命令窗口中執(zhí)行 set HTTPS=true&&npm start 改成https 安全協(xié)議 var protocol = process.env.HTTPS === 'true' ? "https" : "http"; var host = process.env.HOST || 'localhost'; setupCompiler(host, port, protocol); // 編譯源碼 ,生成路徑 runDevServer(host, port, protocol); //啟動 http服務(wù)器 } //配置http服務(wù)器 function runDevServer(host, port, protocol) { var devServer = new WebpackDevServer(compiler, { compress: true, clientLogLevel: 'none', contentBase: paths.appPublic, //根據(jù)導(dǎo)入的paths 指定應(yīng)用根目錄(即index.html所在目錄) hot: true, publicPath: config.output.publicPath, //根據(jù)導(dǎo)入的 config 變量,指定 虛擬目錄,自動指向path編譯目錄(/assets/ => /build/js/)。html中引用js文件時, //必須引用此虛擬路徑(但實際上引用的是內(nèi)存中的文件,既不是/build/js/也不是/assets/)。 quiet: true, watchOptions: { ignored: /node_modules/ }, // Enable HTTPS if the HTTPS environment variable is set to 'true' https: protocol === "https", host: host }); /** * 省略其他代碼 */ openBrowser(protocol + '://' + host + ':' + port + '/'); // 打開瀏覽器 向服務(wù)器發(fā)送請求 }); } function setupCompiler(host, port, protocol) { compiler = webpack(config, handleCompile); // 根據(jù)導(dǎo)入的 config 變量 指向的 webpack.config.dev 配置文件 運行 /** * 省略其他代碼 */ }

?start.js 文件代碼 中 導(dǎo)入了 ?my-app\node_modules\react-scripts\config文件夾下的 ?webpack.config.dev.js 與 paths.js
paths.js ?代碼節(jié)選如下:

var appDirectory = fs.realpathSync(process.cwd()); // 獲取npm run start 運行所在的路徑 function resolveApp(relativePath) { return path.resolve(appDirectory, relativePath); } module.exports = { appPath: resolveApp('.'), ownPath: resolveApp('node_modules/react-scripts'), appBuild: resolveApp('build'), appPublic: resolveApp('public'), appHtml: resolveApp('public/index.html'), // 這就是 一開始 我們的項目 要使用public/index.html作為 默認(rèn)首頁 // 這里寫什么文件名,項目中就要使用什么文件名 包括 也要有public文件夾 appIndexJs: resolveApp('src/index.js'), //編譯的入口文件的文件名 項目中要包括src文件夾 appPackageJson: resolveApp('package.json'), appSrc: resolveApp('src'), yarnLockFile: resolveApp('yarn.lock'), testsSetup: resolveApp('src/setupTests.js'), appNodeModules: resolveApp('node_modules'), // this is empty with npm3 but node resolution searches higher anyway: ownNodeModules: resolveOwn('node_modules'), nodePaths: nodePaths, publicUrl: getPublicUrl(resolveApp('package.json')), servedPath: getServedPath(resolveApp('package.json')) }; /** * 省略其他代碼 */

webpack.config.dev.js ?代碼節(jié)選如下:

var paths = require('./paths'); //也導(dǎo)入了 同文件夾下的 paths.js module.exports = { entry: [ require.resolve('react-dev-utils/webpackHotDevClient'), require.resolve('./polyfills'), paths.appIndexJs // 編譯的入口文件 ], output: { path: paths.appBuild, pathinfo: true, filename: 'static/js/bundle.js', // 只是編譯后生成的目標(biāo)文件 ,這就是一開始我們 打開瀏覽器按f12看到的index.html導(dǎo)入的 // <script type="text/javascript" src="/static/js/bundle.js"></script> publicPath: publicPath }, /** * 省略其他代碼 */ }

已經(jīng)搭建好運行環(huán)境了,接下來 如何開發(fā)app

導(dǎo)入組件

由于babel依賴,這個項目支持es6模塊
當(dāng)你仍然使用require() and module.exports ,我們鼓勵你去使用import and export 替代.
例如:?
Button.js

import React, { Component } from 'react'; class Button extends Component { render() { // ... } } export default Button; // 不要忘記去使用 export default!

DangerButton.js

import React, { Component } from 'react'; import Button from './Button'; //從另一個文件導(dǎo)入一個組件 class DangerButton extends Component { render() { return <Button color="red" />; } } export default DangerButton;

增加樣式
Button.css

.Button { padding: 20px; }

Button.js

import React, { Component } from 'react'; import './Button.css'; // 告訴webpack Button.js 使用這些樣式 class Button extends Component { render() { // You can use them as regular CSS styles return <div className="Button" />; } }

Autoprefixer

react-scripts 通過Autoprefixer 幫你的css文件自動添加瀏覽器兼容前綴
例如:

.App { display: flex; flex-direction: row; align-items: center; }

變成

.App { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -webkit-box-align: center; -ms-flex-align: center; align-items: center; }

增加CSS預(yù)處理器

首先在 my-app/ ?目錄下 ?安裝node-sass用來將scss編譯成css

npm install node-sass --save-dev

打開my-app/package.json,增加以下代碼到scripts中

"scripts": { + "build-css": "node-sass src/ -o src/", + "watch-css": "npm run build-css && node-sass src/ -o src/ --watch", "start": "react-scripts start", "build": "react-scripts build", ...... }

現(xiàn)在你可以重新命名my-app/src/App.css?to?my-app/src/App.scss?and 運行 ??npm run watch-css
或者你可以改成

"scripts": { "build-css": "node-sass src/ -o src/", "start": "npm run build-css && react-scripts start", //先執(zhí)行 build-css 再執(zhí)行 react-scripts start "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }

直接 npm run start

增加圖片

import React from 'react'; import logo from './logo.png'; // 告訴webpack 這個js文件使用這張圖片 console.log(logo); // /logo.84287d09.png 會改變圖片的名字 function Header() { //導(dǎo)入結(jié)果是這個圖片的url地址 return <img src={logo} alt="Logo" />; } export default Header;

當(dāng)項目構(gòu)建的時候,Webpack將正確的移動圖片到構(gòu)建的文件夾下,提供我們正確的路徑

在css工作中的方式也一樣

.Logo { background-image: url(./logo.png); }

webpack發(fā)現(xiàn)所有的相對模塊, 以 ./ ?開始

增加 bootstrap
在react+es6 moudle+bootstrap
你不是一定要React Bootstrap和React 一起使用,但是他是流行的庫去整合 bootstrap 和react應(yīng)用程序,如果你需要他,你可以通過Create React App整合他,通過以下幾個步驟

首先安裝React Bootstrap and Bootstrap從npm,React Bootstrap 不包括Bootstrap CSS ,所以你需要去安裝
在?my-app/ ?目錄下??安裝

npm install react-bootstrap --save npm install bootstrap@3 --save

修改?my-app/src/index.js

在你的src/index.js 文件內(nèi)容的頂部,導(dǎo)入 Bootstrap CSS 和可選的 Bootstrap theme CSS

import React from 'react'; import ReactDOM from 'react-dom'; import 'bootstrap/dist/css/bootstrap.css'; // 必須的 import 'bootstrap/dist/css/bootstrap-theme.css'; // 可選的 import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );

修改 my-app/src/App.js

import React, { Component } from 'react'; import { Grid, Navbar, Jumbotron, Button } from 'react-bootstrap'; class App extends Component { render() { return ( <div> <Navbar inverse fixedTop> <Grid> <Navbar.Header> <Navbar.Brand> <a href="/">React App</a> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> </Grid> </Navbar> <Jumbotron> <Grid> <h1>Welcome to React</h1> <p> <Button bsStyle="success" bsSize="large" href="http://react-bootstrap.github.io/components.html" target="_blank"> View React Bootstrap Docs </Button> </p> </Grid> </Jumbotron> </div> ); } } export default App;

最后 運行

npm run start

參考鏈接?https://github.com/facebookincubator/create-react-app

參考資料:https://blog.csdn.net/github_squad/article/details/57452333

轉(zhuǎn)載于:https://my.oschina.net/lixiaoyan/blog/1796906

總結(jié)

以上是生活随笔為你收集整理的使用 create-react-app 构建 react应用程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。