create-react-app配置多入口專案開發
阿新 • • 發佈:2018-12-21
1. 使用create-react-app腳手架搭建react專案
新建專案資料夾,install create-react-app
npm install -g create-react-app
進入到專案資料夾中:
create-react-app app
cd app
啟動專案:
npm start
2. 將專案webpack配置項分離開
npm run eject
此過程對create-react-app是不可逆的過程。 執行完此命令後會在app的目錄下生成一個config資料夾,裡面有webpack.config.dev.js等檔案,具體如下圖所示:
3. 修改config目錄下的webpack.config.dev.js檔案
在此專案中我配置四個入口檔案,分別是home.html, info.html, user.html, index.html。
a. 修改入口配置:
在webpack.config.dev.js檔案中的entry中修改:
注意: 如果entry只有一個入口檔案的時候是一個數組,有多個入口檔案的時候則改為一個物件
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中修改如下:
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中修改如下:
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物件中:
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. 啟動配置好多入口的專案
npm start (yarn start)