当前位置:首页 > Web开发 > 正文

webpack开发环境速度优化

2024-03-31 Web开发

随着项目的增大,项目运行速度会越来越慢,导致影响开发进度。需要提升开发时代码的运行速度。

1. ScopeHoisting作用域提升

该插件在production模式下默认开启。development下需要手动启动。

1 .使用条件

和TreeShaking一样,必须使用ES6的模块,使用import/export语法。

2. 优点:

1)节省内存开销。因为默认每个bundle会打成闭包。

2)减少体积,,提升速度。因为如果不使用es模块,默认会包裹一层require。

3. 用法

1. 首先阻止babel将es6的模块进行转换

{ test: /\.jsx?$/, use: { loader: ‘babel-loader‘, options: { // 切记modules: false presets: [[‘@babel/preset-env‘, {modules: false}], ‘@babel/preset-react‘], plugins: [ [‘@babel/plugin-proposal-decorators‘, {legacy: true}], [‘@babel/plugin-proposal-class-properties‘, {loose: true}] ] }, }, exclude: /node_modules/ }

2. 引入的第三方库尽量使用es版本

3. 在plugins中配置插件

plugins: [ new webpack.optimize.ModuleConcatenationPlugin(), ]

4. node_modules中的模块优先使用指向es模块的文件

resolve: { mainFields: [‘jsnext:main‘, ‘browser‘, ‘main‘] },

2. 热更新

当项目特别大时,页面重新加载会非常缓慢,可以通过热更新,只更改修改的部分。

1. sevServer中开启热更新

module.exports = { ... devServer: { hot: true //默认开启webpack.HotModuleReplacementPlugin } }

2. css样式热更新

开发模式下使用style-loader, 默认实现了HMR。(css-hot-loader在hot:true时有问题)

{ test: /\.css$/, use: [ ‘style-loader‘, ‘css-loader‘ ] },

3. jsx代码热更新

使用react-hot-loader插件,在需要的模块包裹hot函数。

{ test: /\.jsx?$/, use: { loader: ‘babel-loader‘, options: { presets: [[‘@babel/preset-env‘, {modules: false}], ‘@babel/preset-react‘], plugins: [ [‘@babel/plugin-proposal-decorators‘, {legacy: true}], [‘@babel/plugin-proposal-class-properties‘, {loose: true}], [‘react-hot-loader/babel‘] ] }, }, exclude: /node_modules/ },

在代码中使用hot方法

import React from ‘react‘; import { hot } from ‘react-hot-loader/root‘; function Test(props) { return( <div className="hehe">ppp</div> ) } export default process.env.NODE_ENV === ‘development‘ ? hot(Test) : Test;

也可以不使用该插件,自己实现逻辑

// 尽量在子组件实现该逻辑;它不接受css文件的变化 if(module.hot) { module.hot.accept([‘./example.js‘], () => { ReactDOM.render(<App/>, window.root) }) }

webpack开发环境速度优化

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/40438.html