美文网首页
webpack4升级笔记

webpack4升级笔记

作者: FEDEA | 来源:发表于2019-01-31 11:17 被阅读0次

    shop在webpack4的升级过程被HMR问题卡了很久,最近终于解决,有时间重新梳理并对升级过程踩的坑做下笔记。

    1. 把webpack、webpack-dev-middleware、webpack-dev-server、webpack-hot-middleware都升级到最新版本。
    npm install webpack webpack-dev-middleware webpack-dev-server webpack-hot-middleware --save-dev
    
    1. 升级loaders,修改webpack loader的rules配置结构,从webpack2开始loader已经全部改成了rules的写法。
    npm install bundle-loader css-loader file-loader less-loader postcss-loader sass-loader style-loader url-loader postcss-modules-values less precss base64-loader
    
    mode: 'development',
    loaders: [
                {
                    test: /\.js$/,
                    loaders: ['babel'],
                    exclude: /node_modules/
                }
              ...
    ]
    
    • 重新打包Dll。
    • 增加webpack mode配置。
    • postcss的配置从webpack配置里放到了单独的文件postcss.config.js。
    • 去除OccurenceOrderPlugin、DedupePlugin和CommonsChunkPlugin等插件。
    • ExtractTextWebpackPlugin调整,选用新的CSS文件提取插件mini-css-extract-plugin。
    • fs.walk在fs-extra 2.0.0以后移除,换成klaw
    • res.send(status, content) => res.status(status).send(content)

    webpack 4取消了四个常用的用于性能优化的plugin(UglifyjsWebpackPlugin,CommonsChunkPlugin,ModuleConcatenationPlugin,NoEmitOnErrorsPlugin),转而提供了一个名为optimization的配置项,用于接手以上四位的工作。在webpack4,我们熟悉的CommonsChunkPlugin被splitChunks取代,另外runtimeChunk用于分开打包runtime。DllPlugin因为无法应用tree shaking,一般服务于develop环境。shop可以考虑优化成production环境使用splitChunks和runtimeChunk,develop环境使用DllPlugin。

    1. 升级babel8
    npm uninstall babel-core babel-eslint babel-loader babel-plugin-transform-class-properties babel-plugin-transform-decorators-legacy babel-plugin-transform-object-rest-spread babel-plugin-transform-omodule-variable babel-polyfill babel-preset-env babel-preset-react babel-preset-react-hmre --save-dev
    npm i @babel/core @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators @babel/plugin-proposal-export-default-from @babel/plugin-proposal-export-namespace-from @babel/plugin-syntax-dynamic-import @babel/plugin-transform-runtime @babel/preset-env @babel/preset-react @babel/runtime babel-eslint babel-loader babel-plugin-dynamic-import-node babel-plugin-syntax-dynamic-import babel-plugin-transform-omodule-variable --save-dev
    

    修改babel配置

    {
        "presets": ["@babel/preset-react",
            [
                "@babel/preset-env",
                {
                    "loose": true
                }
            ]
        ],
        "plugins": [
            "transform-omodule-variable",
            ["@babel/plugin-proposal-decorators", { "legacy": true }],
            "@babel/plugin-proposal-class-properties",
            "@babel/plugin-proposal-export-default-from",
            "@babel/plugin-proposal-export-namespace-from",
            "@babel/plugin-transform-runtime",
            ["react-hot-loader/babel"],
            ["@babel/plugin-syntax-dynamic-import"]
        ]
    }
    

    enable inline javascript for less-loader

                {
                    test: /\.less$/,
                    use: [
                        'style-loader',
                        'css-loader',
                        'postcss-loader',
                        {
                            loader: 'less-loader',
                            options: {
                                javascriptEnabled: true
                            }
                        }
                    ]
                }
    
    • It's no longer allowed to omit the '-loader' suffix when using loaders.
      You need to specify 'bundle-loader' instead of 'bundle'

    按提示解决了一些小问题,这时候项目应该可以跑起来了。接下来说说HMR的解决方案。HMR之所以会出问题是因为omodule的require.context涉及到code splitting,更新之后的hot-update过程中,动态加载的组件不知道怎么刷新自己导致的。按照react-hot-loader的文档给组件包上RHL friendly的兼容库(例如 Loadable Components)之后还是无法解决。几经周折,最后尝试出在所有动态分割的组件加上hot方法:

    • babel-preset-react-hmre => react-hot-loader
    • require => import,RHL just support hot import component
    • '../../configs/' + props.productId + '.js' => ../../configs/${props.productId}.js
    • getComponent =>component (async)
    • route.js里,对每个component包上hot方法
    process-update.js:22 Ignored an update to unaccepted module ./node_modules/babel-loader/lib/index.js!./src/omodules/one-page-insurance/pages/OnePageDetail.js -> ./node_modules/bundle-loader/index.js!./src/omodules/one-page-insurance/pages/OnePageDetail.js -> ./src/omodules/one-page-insurance/route.js -> ./src/omodules/one-page-insurance/omodule.js -> ./src sync recursive ^\.\/omodules\/((?!\/)[\s\S])+\/omodule\.js$ -> ./src/omodule.js -> ./src/root/store/configureStore.dev.js -> ./src/root/store/configureStore.js -> ./src/root/index.js -> 0
    onUnaccepted @ process-update.js:22
    hotApply @ bootstrap:502
    cb @ process-update.js:66
    (anonymous) @ process-update.js:82
    Promise.then (async)
    check @ process-update.js:81
    ./node_modules/webpack-hot-middleware/process-update.js.module.exports @ process-update.js:42
    processMessage @ client.js:268
    handleMessage @ client.js:136
    handleMessage @ client.js:99
    process-update.js:95 [HMR] The following modules couldn't be hot updated: (Full reload needed)
    This is usually because the modules which have changed (and their parents) do not know how to hot reload themselves. See https://webpack.js.org/concepts/hot-module-replacement/ for more details.
    
    /**
     * omodule 描述文件
     * 大多数情况不需要修改该文件。新建一个模块,复制粘贴该文件即可
     * {
     *      route,
     *      reducer,   //一个omodule模块可以没有reducer
     *      childOmodules
     * }
     *
     */
    import { hot } from 'react-hot-loader/root'
    
    export const namespace = __omodule_namespace
    
    const routes = require('./route').default
    routes.childRoutes = routes.childRoutes.map(({ path, component }) => {
        return {
            path,
            component: hot(component)
        }
    })
    
    const omodule = {
        route: routes,
        // 异步reducer写法:
        //      一般情况下都推荐用异步reducer,
        //      只有当进入该omudle模块下的路由时异步reducer才会被加载
        //
        reducer: cb => {
            import('./reducer/index.js').then(function(reducerFun) {
                const reducer = {}
                reducer[namespace] = reducerFun.default
                cb(null, reducer)
            })
        },
        // 同步reducer写法: 整个项目初始化就会加载该reducer
        //
        // reducer: {
        //     [`${namespace}`]: require('./reducer').default
        // },
        childOmodules: (r => {
            return r.keys().map(key => r(key).default)
        })(require.context('./', true, /^\.\/omodules\/((?!\/)[\s\S])+\/omodule\.js$/))
    }
    
    export default omodule
    

    升级过程中发现webpack由4.23升级到4.29之后会报错,缺少解析动态import的loader,应该是plugin-syntax-dynamic-import不兼容4.29的webpack,回退到4.23。

    HMR参考资料

    https://github.com/gaearon/react-hot-loader
    https://github.com/gaearon/react-hot-boilerplate
    https://github.com/gaearon/react-hot-loader/blob/master/docs/Troubleshooting.md
    https://webpack.docschina.org/guides/hot-module-replacement
    https://github.com/gaearon/react-hot-loader/issues/288
    https://github.com/gaearon/react-hot-loader/issues/249

    其他

    https://github.com/jprichardson/node-fs-extra/issues/338
    https://segmentfault.com/a/1190000005614604
    http://www.voidcn.com/article/p-sfoxvjwp-bbs.html
    http://acgtofe.com/posts/2016/02/full-live-reload-for-express-with-webpack
    https://zhuanlan.zhihu.com/p/35407642

    相关文章

      网友评论

          本文标题:webpack4升级笔记

          本文链接:https://www.haomeiwen.com/subject/qvmflqtx.html