Hshen
人若无名 便可潜心练剑
GitHub Abou byHshen Hshen

create-react-app 多入口配置

2024年4月25日

预计阅读:2min

文件目录

├── README.md
├── config
│   ├── env.js
│   ├── getHttpsConfig.js
│   ├── jest
│   │   ├── babelTransform.js
│   │   ├── cssTransform.js
│   │   └── fileTransform.js
│   ├── modules.js
│   ├── paths.js
│   ├── webpack
│   │   └── persistentCache
│   │       └── createEnvironmentHash.js
│   ├── webpack.config.js
│   └── webpackDevServer.config.js
├── package.json
├── public
│   ├── favicon.ico
│   ├── index.html
│   ├── logo192.png
│   ├── logo512.png
│   ├── manifest.json
│   └── robots.txt
├── scripts
│   ├── build.js
│   ├── start.js
│   └── test.js
└── src
    ├── dist
    │   ├── clear.js
    │   ├── favicon.png
    │   └── manifest.json
    └── pages
        ├── background
        │   ├── eventSource.js
        │   ├── index.html
        │   └── index.js
        ├── content
        │   ├── index.js
        │   └── reload.js
        ├── panel
        │   └── index.js
        └── popup
            ├── index.html
            ├── index.js
            └── popup.css

修改文件 paths.js

// 多入口配置
const pageDirectory = resolveApp('src/pages');
const list = fs.readdirSync(pageDirectory);
const entry = list.reduce((entry, item) => {
  return {
    ...entry,
    [item]: `${pageDirectory}/${item}/index.js`,
  }
}, {});
// 过滤有HTML
const htmlList = list.filter(item => fs.existsSync(`${pageDirectory}/${item}/index.html`));
 
module.exports = {
  // ...
  entry,
  list,
  htmlList,
};

修改文件 start.js

// 注释校验
// if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
//   process.exit(1);
// }

修改文件 webpack.config.js

{
  // ...
  entry: paths.entry, 
  filename: '[name].js',
  chunkFilename: '[name].chunk.js',
    plugins: [
    //...
    ...paths.htmlList.map(name => new HtmlWebpackPlugin(
      Object.assign(
        {},
        {
          inject: true,
          chunks: [`${name}`],
          template: paths.appHtml,
          filename: `${name}.html`,
        },
        isEnvProduction
          ? {
            minify: {
              removeComments: true,
              collapseWhitespace: true,
              removeRedundantAttributes: true,
              useShortDoctype: true,
              removeEmptyAttributes: true,
              removeStyleLinkTypeAttributes: true,
              keepClosingSlash: true,
              minifyJS: true,
              minifyCSS: true,
              minifyURLs: true,
            },
          }
          : undefined
      )
    )),
    //   ...
    new WebpackManifestPlugin({
    //   ...
      generate: {
        // ...
        // const entrypointFiles = entrypoints.main.filter(
        //   fileName => !fileName.endsWith('.map')
        // );
        const entrypointFiles = Object.keys(entrypoints).reduce((pre, current) => {
          const temp = entrypoints[current].filter(fileName => !fileName.endsWith('.map'));
          return [...pre, ...temp];
        }, []);
      }
    })
  ]
}