现在开始在ide环境中一步一步创建react项目
一:新建项目文件夹,然后用vscode打开
二:在终端输入npm init 全部默认
三:在项目根目录创建dist和src文件夹
四:src下创建index.html和index.js
五:安装webpack,运行npm i webpack -D 和 npm i webpack-cli -D
4版本后需要多加webpack-cli,4版本前只安装webpack 就够了,这安装的最新版的4.5.0
安装过程中如果报错安装失败可以运行npm cache clean --force 清除本地缓存
windows不是全局安装,会找不到webpack命令,需要进入本地的node_modules/.bin下执行
所以打包命令需要这样执行:node_modules/.bin/webpack
六:在根目录下创建 webpack.config.js文件
七:安装插件
npm i html-webpack-plugin -D html打包插件
npm i babel-loader babel-core babel-preset-env -D es6 npm
npm i babel-preset-react -D 安装reaact转换插件
npm i react react-dom -S 安装react
npm i style-loader css-loader -D css打包插件
npm i extract-text-webpack-plugin -D 把css拆成独立文件
npm i sass-loader node-sass -D sass转换插件
npm i file-loader url-loader -D 文件加载插件
npm i webpack-dev-server -D 为webpack项目提供web服务
会遇到Error: Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead的错,是因为extract-text-webpack-plugin最新版本还不支持webpack4,x版本。解决方法是执行 npm i extract-text-webpack-plugin@next -D
八:配置webpack.config.js
const path
=
require(
'path');
const HtmlWebpackPlugin
=
require(
'html-webpack-plugin');
const ExtractTextPlugin
=
require(
"extract-text-webpack-plugin");
//对外的打包配置对象
module.
exports
={
mode
:
"development",
//必须,开发环境或生产环境,development,production
//输出配置
output
: {
path
:
path.
resolve(
__dirname,
'dist'),
//publicPath:'./dist/',//webpack-dev-server运行后从根目录引用文件,用了后devServer里的contentBase就可以不要了
filename
:
'js/index.js'
},
//babel语法转换规则
module
: {
rules
: [
{
test
:
/\.js
$
/,
exclude
:
/(node_modules
|
bower_components)/,
use
: {
loader
:
'babel-loader',
options
: {
presets
: [
'env',
'react']
}
}
},
{
test
:
/\.css
$
/,
use
:
ExtractTextPlugin.extract({
fallback
:
"style-loader",
use
:
"css-loader"
})
},
{
test
:
/\.scss
$
/,
use
:
ExtractTextPlugin.extract({
use
: [{
loader
:
"css-loader",
}, {
loader
:
"sass-loader"
}],
fallback
:
"style-loader"
})
},
{
test
:
/\.(png
|
jpg
|
gif)
$
/,
use
: [
{
loader
:
'url-loader',
options
: {
limit
:
8192,
name
:
'resource/[name].[ext]'
}
}
]
},
{
test
:
/\.(png
|
jpg
|
gif)
$
/,
use
: [
{
loader
:
'file-loader',
options
: {
name
:
'resource/[name].[ext]'
}
}
]
}
]
},
//插件
plugins
: [
new
HtmlWebpackPlugin({
template
:
path.
join(
__dirname,
'src/index.html'),
filename
:
'index.html'
}),
new
ExtractTextPlugin(
"css/[name].css")
],
devServer
: {
port
:
8081
},
}
九:在package配置快速命令
十:善未解决的问题
图片加上后没有效果,不知道是啥原因