create-react-app配置多入口项目开发

1. 使用create-react-app脚手架搭建react项目

新建项目文件夹,install create-react-app

1
npm install -g create-react-app

进入到项目文件夹中:

1
2
create-react-app app
cd app

启动项目:

1
npm start

2. 将项目webpack配置项分离开

1
npm run eject

此过程对create-react-app是不可逆的过程。
执行完此命令后会在app的目录下生成一个config文件夹,里面有webpack.config.dev.js等文件,具体如下图所示:

config

3. 修改config目录下的webpack.config.dev.js文件

在此项目中我配置四个入口文件,分别是home.html, info.html, user.html, index.html。

a. 修改入口配置:

在webpack.config.dev.js文件中的entry中修改:

注意: 如果entry只有一个入口文件的时候是一个数组,有多个入口文件的时候则改为一个对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
entry: {
home: [
require.resolve('react-error-overlay'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs,
],

info: [
require.resolve('react-error-overlay'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appSrc + '/barrage.js'
],

user: [

require.resolve('react-error-overlay'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appSrc + '/lottery.js'
],

index: [
require.resolve('react-error-overlay'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appSrc + '/singIn.js'

]
},

b. 修改出口配置:

在webpack.config.dev.js文件中的output中修改如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
output: {
path: paths.appBuild,

pathinfo: true,

filename: 'static/js/[name].bundle.js',

chunkFilename: 'static/js/[name].chunk.js',

publicPath: publicPath,

devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},

c. 修改生成html模板插件HtmlWebpackPlugin:

在webpack.config.dev.js文件中的plugins中修改如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
plugins: [
new HtmlWebpackPlugin({
inject: true,
chunks: ["home"],
template: paths.appHtml,
}),

new HtmlWebpackPlugin({
inject: true,
chunks: ["info"],
template: paths.appHtml,
filename: 'info.html'
}),

new HtmlWebpackPlugin({
inject: true,
chunks: ["user"],
template: paths.appHtml,
filename: 'user.html'
}),

new HtmlWebpackPlugin({
inject: true,
chunks: ["index"],
template: paths.appHtml,
filename: 'index.html'
}),


//其他配置
]

4. 修改config目录下的webpack.config.prod.js文件

entry的修改, output的修改和HtmlWebpackPlugin的修改和webpack.config.dev.js中的修改一模一样

5. 修改config目录下的webpackDevServer.config.js文件

该文件的修改主要是为了指明哪些路径映射到哪个html文件

修改点是在historyApiFallback对象中:

1
2
3
4
5
6
7
8
9
10
historyApiFallback: {

disableDotRule: true,
rewrites: [
{from: /^\/home.html/, to: 'build/home.html'},
{from: /^\/info.html/, to: 'build/info.html'},
{from: /^\/user.html/, to: 'build/user.html'},
{from: /^\/index.html/, to: 'build/index.html'},
]
},

6. 启动配置好多入口的项目

1
npm start (yarn start)
baishiwen wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!