欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2020 React 创建MPA多页面代码框架。顺便解决 Cannot read property ‘filter’ of undefined问题

程序员文章站 2022-07-02 22:37:46
...

本文讲述如何使用React 创建MPA多页面代码框架,主要分两个大步骤进行:
看这篇文章的,大多是同行,直接上干货!

第一步 建立代码框架

1、npx create-react-app train-green

使用npx避免全局安装React到你机器上,占用你的空间

2、npm run eject

使用此命令,是因为大型项目往往需要对webpack配置进行修改

3、npm start,确保正常运行

4、安装必要的包

大型项目一般都包括以下常用的包
npm i redux react-redux redux-thunk --save
npm i normalize.css --save

5、删掉src目录下除 serviceWork.js之外文件

为了下一步重构目录结构

6、在src下新建 index目录,在目录下建7个文件,依次是

 index.js, index.css, App.jsx, App.css, reducers.js, actions.js, store.js

7、编写index.js内容框架

index是为了挂接App到html的root上,做了这一步,你就可以在App上尽情发挥了

import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import store from './store'
import App from './App.jsx'
import 'normalize.css/normalize.css'
import './index.css'

ReactDOM.render(
    <Provider store = {store}>
        <App/>
    </Provider>,
    document.getElementById('root')
)

8、编写App.jsx

一般需要使用connect对其进行包裹

import {connect} from 'react-redux'
import './App.css'

function App(props) {

}

export default connect(
    function mapStateToProps(state) {},
    function mapDispatchToProps(dispatch) {}
)(App)

9、编写reducers.js

export default {}

10、编写store.js

import { createStore, combineReducers, applyMiddleware} from 'redux'

import reducers from './reducers'
import thunk from 'redux-thunk'

export default createStore(
    combineReducers(reducers),
    {},
    applyMiddleware(thunk)
)

11、修改config/paths.js中路径

因为已经修改了目录结构,这里需要修改一下

appIndexJs: resolveModule(resolveApp, 'src/index/index'),

12、运行 npm run build保证正常编译

第二步 支持多页面

1、拷贝src/index目录到同级目录,并重命名,一个目录对应一个页面,例如,这里拷贝index目录为 query目录

2020 React 创建MPA多页面代码框架。顺便解决 Cannot read property ‘filter’ of undefined问题

2、拷贝public/index.html 为query.html

3、修改config/paths.js

appHtml: resolveApp('public/index.html'),
appQueryHtml: resolveApp('public/query.html'),
appIndexJs: resolveModule(resolveApp, 'src/index/index'),
appQueryJs: resolveModule(resolveApp, 'src/query/index'),

4、修改webpack.config.js以使编译支持MPA多页面。

修改entry 部分:

 entry: {
      index:[
              isEnvDevelopment && require.resolve('react-dev-utils/webpackHotDevClient'),
              paths.appIndexJs,
            ].filter(Boolean),
      query:[
              isEnvDevelopment && require.resolve('react-dev-utils/webpackHotDevClient'),
              paths.appQueryJs,
            ].filter(Boolean),
    },

5、修改webpack.config.js以使编译支持MPA多页面。

修改plugins部分:

 new HtmlWebpackPlugin(
        Object.assign(
          {},
          {
            inject: true,
            template: paths.appHtml,
            filename: 'index.html',
            chunks: ['index'],
          },
          isEnvProduction
            ? {
                minify: {
                  removeComments: true,
                  collapseWhitespace: true,
                  removeRedundantAttributes: true,
                  useShortDoctype: true,
                  removeEmptyAttributes: true,
                  removeStyleLinkTypeAttributes: true,
                  keepClosingSlash: true,
                  minifyJS: true,
                  minifyCSS: true,
                  minifyURLs: true,
                },
              }
            : undefined
        )
      ),
      new HtmlWebpackPlugin(
        Object.assign(
          {},
          {
            inject: true,
            template: paths.appQueryHtml,
            filename: 'query.html',
            chunks: ['query'],
          },
          isEnvProduction
            ? {
                minify: {
                  removeComments: true,
                  collapseWhitespace: true,
                  removeRedundantAttributes: true,
                  useShortDoctype: true,
                  removeEmptyAttributes: true,
                  removeStyleLinkTypeAttributes: true,
                  keepClosingSlash: true,
                  minifyJS: true,
                  minifyCSS: true,
                  minifyURLs: true,
                },
              }
            : undefined
        )
      ),

6、使用 npm run build 编译

很遗憾,你将碰到如下问题:报Cannot read property ‘filter’ of undefined

7、修改webpack.config.js

注释掉entrypoint相关部分

 new ManifestPlugin({
  fileName: 'asset-manifest.json',
  publicPath: paths.publicUrlOrPath,
  generate: (seed, files, entrypoints) => {
     const manifestFiles = files.reduce((manifest, file) => {
       manifest[file.name] = file.path;
       return manifest;
     }, seed);
     //const entrypointFiles = entrypoints.main.filter(
     //  fileName => !fileName.endsWith('.map')
     //);

     return {
       files: manifestFiles,
       //entrypoints: entrypointFiles,
     };
  },
}),

8、再运行 npm run build,完美收官

2020 React 创建MPA多页面代码框架。顺便解决 Cannot read property ‘filter’ of undefined问题

相关标签: React开发系列