This year the company has been in the front and rear end implement separate development, there just needs active development, so would like to react with a multi-page application to be realized. The project is developed on the basis of create-react-app (@ 3.0.1) on the scaffolding.
Ready to work
Download and install the create-react-app (@ 3.0.1 , other versions may be slightly different configuration) scaffolding and CRA configuration all decompile to the current project (Reference: juejin.im/post/5a5d5b...
Create folders constraint specification
Specified as follows (refer to micro-channel applet file folder specification)
Modify the configuration webpack
First modify paths.js file config folder, add the following function:
// 添加获取多页html模板方法
const getMultiPageHtml = (filePath) => {
return globby.sync(filePath, {
expandDirectories: {
files: ['*.html']
}
})
.reduce((arr, file) => {
let key = file.replace(/(^src\/|\.html$)/g, '');
return arr.concat([[
key, // 入口 chunk key(用文件路径可保证key唯一性)
resolveApp(file), //html template url
resolveApp(`src/${key}.js`) //入口js文件 url
]])
}, []);
}
复制代码
paths.js export value added multiPageList value:
Webpack.config.js modify the file, add the following function:
// 新增获取多页面配置
const getMultiPageConfig = (files) => {
return files.reduce((data, file) => {
const [key, template, appJs] = file;
if( fs.existsSync( appJs ) ){
data.entryJs[key] = [
isEnvDevelopment &&
require.resolve('react-dev-utils/webpackHotDevClient'),
appJs
].filter(Boolean);
data.htmlPlugins.push(
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
chunks: [key],
template: template,
filename: `${key}.html`
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
)
)
}
return data;
}, {
entryJs: { },
htmlPlugins: [ ]
})
}
const { entryJs, htmlPlugins } = getMultiPageConfig(paths.multiPageList);
复制代码
Then modifications and plugins entry configuration items:
Since a multi-page application based CRA webpack configuration is complete, the other configuration optimization can be adjusted according to their needs.
The current arrangement has the advantage
- After adding configure and does not require manual entry file htmlWebpackPlugin, as long as the file is automatically generated based directory specification.
- Support multi-level folder, file folder directory structure to generate consistent with the source folder.
Shortcoming
- Current development activities due to fewer pages, yet found the problem, if you have questions please leave a message discussion in use.
Reproduced in: https: //juejin.im/post/5d08b1d1e51d45554877a5e1