开始之前在书写文章之前,我假设大家已经有了 javascript,node 包管理工具,linux 终端操作 这些基本技能,接下来,我将一步一步指引大家从头搭建一个 react 项目
最终实现的效果我们将使用 webpack 和 babel 搭建一个 react 应用,我们的目的很清晰,就是 更好的理解和掌握这些工具的使用
我们创建的应用程序既要做到 最小,也要遵循 最佳实践,为不是特别熟练的同学巩固一下基础
初始化创建你的项目,并添加的你的配置文件 package.json
mkdir webpack-babel-react-revisited
cd webpack-babel-react-revisited
yarn init
webpack我们首先安装 webpack,它是目前非常流行的 模块打包器,它将应用程序包含的每个模块打包成少量的 块,以便这些代码从服务器加载到浏览器中
yarn add webpack --dev
接下来,我们开始书写一些模块。我们将源文件 app.js 保存到 src 目录中
/** app.js */
console.log('hello from 枫上雾棋!');
然后,我们跑一下 webpack
./node_modules/webpack/bin/webpack.js ./src/app.js --output-filename ./dist/app.bundle.js
如果你打开生成的 app.bundle.js,你会发现上面是 webpack 的模块处理代码,下面是我们书写的 console.log
这条指令是将我们的 app.js 作为 webpack 的 入口文件,将结果输出到 dist 文件夹中,指令有些冗长,在实际开发中,我们使用 webpack 配置文件来代替,为了文档结构看起来更加清晰,参考 目录 如下
├── config
│ ├── paths.js
│ ├── webpack.config.prod.js
├── src
│ ├── app.js
├── package.json
下面是参考 配置
paths.js
const path = require('path');
const fs = require('fs');
const appdirectory = fs.realpathsync(process.cwd());
const resolveapp = relativepath => path.resolve(appdirectory, relativepath);
module.exports = {
appdist: resolveapp('dist'),
appsrc: resolveapp('src'),
};
这个文件不是必须的,但在项目增大后,它的意义就瞬间出来了
webpack.config.prod.js
const path = require('path');
const htmlwebpackplugin = require('html-webpack-plugin');
const paths = require('./paths');
const plugins = [
new htmlwebpackplugin({
title: 'webpack babel react revisited',
filename: path.join(paths.appdist, 'index.html'),
}),
];
const config = {
entry: {
app: path.join(paths.appsrc, 'app'),
},
output: {
path: paths.appdist,
filename: 'assets/js/[name].js',
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins,
};
module.exports = config;
这里我们还添加了一个 html-webpack-plugin,它简化了我们 html 文件的创建,安装我们就不再这里赘述了,如果还不知道的同学可以点击链接查看
其中,我们还使用了一个 语法糖,这样在我们导入 .js,.jsx 时就不需要指定扩展名了
接下来,我们指定配置文件再跑一下 webpack
./node_modules/webpack/bin/webpack.js --config config/webpack.config.prod.js
发现除了实现上面的效果外,还自动帮我们生成了一个 index.html,我们可以点击这个 html,在控制台中查看效果,相比上面,是不是方便了很多
当然,最后我们肯定也不是使用这种方式来 build,打开 package.json,添加如下 脚本命令,然后执行 yarn build,是不是瞬间感觉 nice 了很多
"scripts": {
"clean": "rimraf dist *.log .ds_store",
"build": "yarn run clean && webpack --config config/webpack.config.prod.js --progress"
}
webpack dev server除此之外,webpack 为我们提供了一个的 dev server,它还支持 模块热替换
首先,安装 webpack-dev-server
yarn add --dev webpack-dev-server
在 config 目录中添加配置文件 webpack.config.dev.js
const path = require('path');
const htmlwebpackplugin = require('html-webpack-plugin');
const openbrowserplugin = require('open-browser-webpack-plugin');
const paths = require('./paths');
const hostname = process.env.host || 'localhost';
const port = process.env.port || 3000;
const plugins = [
new htmlwebpackplugin({
title: 'webpack babel react revisited',
filename: path.join(paths.appdist, 'index.html'),
}),
new openbrowserplugin({ url: `http://${hostname}:${port}` }),
];
const config = {
entry: {
app: path.join(paths.appsrc, 'app'),
},
output: {
path: paths.appdist,
filename: 'assets/js/[name].js',
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins,
devserver: {
contentbase: paths.appdist,
compress: true,
port,
},
};
module.exports = config;
在 webpack.config.prod.js 的基础上,我们增加了 open-browser-webpack-plugin 插件和 devserver 配置,open-browser-webpack-plugin 插件顾名思义,会帮我们自动打开 dev server 最后返回给我们的地址
更新 package.json
"scripts": {
"clean": "rimraf dist *.log .ds_store",
"webpack:dev":
"node_env=development webpack-dev-server --config config/webpack.config.dev.js --progress",
"webpack:prod":
"node_env=production webpack --config config/webpack.config.prod.js --progress",
"start": "yarn run clean && yarn run webpack:dev",
"build": "yarn run clean && yarn run webpack:prod"
}
现在,我们就可以通过如下方式来启动
yarn start
启动后,有没有瞬间感觉很棒
babel为了能够使用 es6 以及更高版本,我们需要一个 转换编译器,我们选择 babel,它能将 es6 转换成可以在浏览器中运行的代码,除此之外,他还内置了 react jsx 扩展,可以说它的出现推动了 javascipt 的发展
所有,我们安装下面这些依赖包
yarn add --dev babel-loader babel-core babel-preset-env babel-preset-react
创建 babel 默认配置文件 .babelrc
{
"presets": ["env", "react"]
}
这个是告诉 babel 用我们刚刚安装的两个 presets
接下来,更新 webpack 配置文件
config.module = {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
}
更新以后,虽然看不到什么变化,但事实上我们可以使用 es6 了
react最后,我们来添加 react,这也可能是你阅读这篇文章的原因
首先,我们还是先安装它
yarn add react react-dom
用下面代码替换 console.log
import react, { component } from 'react';
import { render } from 'react-dom';
export default class hello extends component {
render() {
return <h1>hello from 枫上雾棋!</h1>;
}
}
render(<hello />, document.getelementbyid('app'));
因为要添加 <p id="app"></p>,所以我们要修改一下 html-webpack-plugin 的配置
new htmlwebpackplugin({
template: path.join(paths.appsrc, 'index.html'),
}),
参考 template 如下
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>webpack babel react revisited</title>
</head>
<body>
<noscript>
you need to enable javascript to run this app.
</noscript>
<p id="app"></p>
</body>
</html>
接下来,就是见证奇迹的时刻
重新启动服务,你有没有发现搭建一个 react 应用程序就这么简单
接下来,大家就可以 自行探索,添加更多的东西来适应自身应用程序的需要
下面再补充一下如何添加 css 和 图片
css每个 web 应用程序都离不开 css,我们在 src 目录中创建 style.css
body,
html,
#app {
margin: 0;
width: 100%;
height: 100%;
}
#app {
padding: 30px;
font-family: '微软雅黑';
}
将其添加到应用程序中我们需要使用 css-loader
如果想将 css 注入 style 标签中,我们还需要 style-loader,通常,是将这两个结合使用
我们使用 extract-text-webpack-plugin 将其解压到外部
为此,我们首先安装
yarn add --dev css-loader style-loader extract-text-webpack-plugin
然后在 app.js 中导入 style.css
import './style.css';
最后更新 webpack 配置文件
config.module = {
rules: [
{
test: /\.css$/,
use: extracttextplugin.extract({
fallback: 'style-loader',
use: 'css-loader',
}),
},
],
}
config.plugins.push([
new extracttextplugin("styles.css"),
])
看起来稍显复杂,但是大功告成,为了更好地使用它,我们都得经历这个过程
重新启动服务,你会发现你的 dist 目录中多了一个 styles.css
图片最后我们增加 file-loader 来处理我们引入的图片等文件
首先,安装 file-loader
yarn add --dev file-loader
我们在 src/images 中放入一张图片,在 app.js 中导入
import avatar from './images/avatar.jpg';
export default class hello extends component {
render() {
return (
<p>
<img src={avatar} alt="avatar" style={{ width: 400, height: 250 }} />
</p>
);
}
}
更新 webpack 配置文件
config.module = {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputpath: 'assets/images/',
},
},
],
},
],
}
重启服务,哈哈
总结如果有什么问题,可以查看 webpack-babel-react-revisited 仓库
现在,大家对搭建 react 应用程序是不是感觉轻松了很多,但 react 整个技术栈并不止包括这些,还有 redux,react router,单元测试,代码校验 等内容,关于 react 其他内容,欢迎查看日志其他文章
以上就是关于webpack, babel 和 react的知识的详细内容。