背景:最近接手一个混合app项目,可是其中的页面都是用jquery写的,有点乱,因此决定用react重构一下,由于涉及到不少页面,因此create-react-app只能本身配置成多页的了。弄这个也弄了挺久的,主要是对webpack的各个配置项不够了解。也走了不少弯路,因此在这就写下来,算做对本身的一个总结。
1.使用create-react-app 建立一个单页应用,而且建立成功以后运行 npm run eject 暴露配置2.在config中修改webpack.config.dev.js文件css
//这里我已经写成对象格式了,有多少个页面就添加多少个key:value对,这里我已经添加了一个admin,数组中的paths.appSrc+'/admin.js'就是这个html页面的入口文件 entry: { index:[ require.resolve('./polyfills'), require.resolve('react-dev-utils/webpackHotDevClient'), paths.appIndexJs, ], admin:[ require.resolve('./polyfills'), require.resolve('react-dev-utils/webpackHotDevClient'), paths.appSrc + '/admin.js', ] }
//多少个页面就new 多少个 HtmlWebpackPlugin 而且在每个里面的chunks都须要和上面的entry中的key匹配,例如上面entry中有index和admin这两个。这里的chunks也须要是index和admin new HtmlWebpackPlugin({ inject: true, chunks:["index"], template: paths.appHtml, }), new HtmlWebpackPlugin({ inject: true, chunks:["admin"], template:paths.appHtml, filename:'admin.html' }),
3.修改config下的webpack.config.prod.js文件
//这里的paths.appIndexJs和paths.appSrc+'/admin.js'依然是每一个html的入口文件 entry:{ index:[ require.resolve('./polyfills'), paths.appIndexJs ], admin:[ require.resolve('./polyfills'), paths.appSrc+'/admin.js' ] }
//和开发环境下同样,多少个html就new多少个 HtmllWebpackPlugin,每一个都须要指定chunks,而且指定filename,在minify中配置是否压缩js、css等,这是生产环境下的配置 new HtmlWebpackPlugin({ inject: true, chunks:["index"], template: paths.appHtml, minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true, }, }), new HtmlWebpackPlugin({ inject: true, chunks:["admin"], template: paths.appHtml, filename:'admin.html', minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true, }, }),
3.在开发环境中若是想经过地址访问不一样的页面,须要修改webpackDevServer.config.js
//这里的rewrites:[ {from: /^\/admin.html/, to: '/build/admin.html' }] 数组里面是一个个对象,对象中前面的值是在开发时候访问的路径,例如 npm run start以后会监听 localhost:3000 ,此时在后面加上 /admin.html就会访问admin.html中的内容,默认是访问index.html;数组中的第二个值是生产环境下的文件的路径。若是有不少页面,就在rewrites中添加更多对象 historyApiFallback: { disableDotRule: true, rewrites: [ { from: /^\/admin.html/, to: '/build/admin.html' }, ] },