Home > Web Front-end > JS Tutorial > body text

How to split code based on webpack

php中世界最好的语言
Release: 2018-03-28 14:51:03
Original
2544 people have browsed it

This time I will show you how to perform code splitting based on webpack, and what are the precautions for code splitting based on webpack. The following is a practical case, let's take a look.

Preface

As the front-end project continues to expand, the js files referenced by an originally simple web application may become increasingly large. Especially in the recent popular single-page applications, there is an increasing reliance on some packaging tools (such as webpack). Through these packaging tools, modules that need to be processed and depend on each other are directly packaged into a separate bundle file, which is loaded when the page is first loaded. When, all js will be loaded. However, there are often many scenarios where we do not need to download all the dependencies of a single-page application at once. For example: We now have a single-page "Order Management" single-page application with permissions. Ordinary administrators can only enter the "Order Management" section, while super users can perform "System Management"; or, we have a huge order management For page applications, users need to wait for a long time to load irrelevant resources when they open the page for the first time. At these times, we can consider performing certain code splitting.

Implementation method

Simple on-demand loading

The core purpose of code splitting is to achieve on-demand resources load. Consider this scenario. In our website, there is a component similar to a chat box in the lower right corner. When we click the circular button, the chat component is displayed on the page.

btn.addEventListener('click', function(e) {
  // 在这里加载chat组件相关资源 chat.js
});
Copy after login
We can see from this example that by binding the operation of loading chat.js to the btn click event, the on-demand loading of the chat component after clicking the chat button can be achieved. The way to dynamically load js resources is also very simple (similar to the familiar jsonp). Just dynamically add the tag to the page and point the src attribute to the resource.

btn.addEventListener('click', function(e) {
  // 在这里加载chat组件相关资源 chat.js
  var ele = document.createElement('script');
  ele.setAttribute('src','/static/chat.js');
  document.getElementsByTagName('head')[0].appendChild(ele);
});
Copy after login
Code splitting is the work done to achieve on-demand loading. Imagine that we use the packaging tool to package all the js into the bundle.js file. In this case, there is no way to achieve the on-demand loading described above. Therefore, we need to talk about the on-demand loading code in Split it out during the packaging process, which is code splitting. So, do we need to manually split these resources? Of course not, you still need to use packaging tools. Next, we will introduce code splitting in webpack.

Code splitting

Here we return to the application scenario and introduce how to perform code splitting in webpack. There are multiple ways to implement code splitting in builds in webpack.

import()

The import here is different from the import when the module is introduced. It can be understood as a function-like function of a dynamically loaded module, passed in The parameters are the corresponding modules. For example, the original module import react from 'react' can be written as import('react'). But it should be noted that import() will return a Promise object. Therefore, it can be used in the following way:

btn.addEventListener('click', e => {
  // 在这里加载chat组件相关资源 chat.js
  import('/components/chart').then(mod => {
    someOperate(mod);
  });
});
Copy after login
As you can see, the method of use is very simple and is no different from the Promise we usually use. Of course, you can also add some

Exception handling:

btn.addEventListener('click', e => {
  import('/components/chart').then(mod => {
    someOperate(mod);
  }).catch(err => {
    console.log('failed');
  });
});
Copy after login
Of course, since import() will return a Promise object, you should pay attention to some compatibility issues. It is not difficult to solve this problem. You can use some Promise polyfills to achieve compatibility. It can be seen that the dynamic import() method is relatively clear and concise in terms of semantics and syntax.

require.ensure()

Written this sentence on the official website of webpack 2:

require.ensure() is specific to webpack and superseded by import().

Therefore, it is not recommended to use the require.ensure() method in webpack 2. But this method is still valid at present, so it can be briefly introduced. It is also available when included in webpack 1. The following is the syntax of require.ensure():

Copy code The code is as follows:

require.ensure(dependencies: String[], callback: function( require), errorCallback: function(error), chunkName: String)

require.ensure() accepts three parameters:

  1. The first parameter dependencies is an array , represents some dependencies of the currently required module;

  2. 第二个参数callback就是一个回调函数。其中需要注意的是,这个回调函数有一个参数require,通过这个require就可以在回调函数内动态引入其他模块。值得注意的是,虽然这个require是回调函数的参数,理论上可以换其他名称,但是实际上是不能换的,否则webpack就无法静态分析的时候处理它;

  3. 第三个参数errorCallback比较好理解,就是处理error的回调;

  4. 第四个参数chunkName则是指定打包的chunk名称。

因此,require.ensure()具体的用法如下:

btn.addEventListener('click', e => {
  require.ensure([], require => {
    let chat = require('/components/chart');
    someOperate(chat);
  }, error => {
    console.log('failed');
  }, 'mychat');
});
Copy after login

Bundle Loader

除了使用上述两种方法,还可以使用webpack的一些组件。例如使用Bundle Loader:

npm i --save bundle-loader
Copy after login

使用require("bundle-loader!./file.js")来进行相应chunk的加载。该方法会返回一个function,这个function接受一个回调函数作为参数。

let chatChunk = require("bundle-loader?lazy!./components/chat");
chatChunk(function(file) {
  someOperate(file);
});
Copy after login

和其他loader类似,Bundle Loader也需要在webpack的配置文件中进行相应配置。Bundle-Loader的代码也很简短,如果阅读一下可以发现,其实际上也是使用require.ensure()来实现的,通过给Bundle-Loader返回的函数中传入相应的模块处理回调函数即可在require.ensure()的中处理,代码最后也列出了相应的输出格式:

/*
Output format:
  var cbs = [],
    data;
  module.exports = function(cb) {
    if(cbs) cbs.push(cb);
      else cb(data);
  }
  require.ensure([], function(require) {
    data = require("xxx");
    var callbacks = cbs;
    cbs = null;
    for(var i = 0, l = callbacks.length; i < l; i++) {
      callbacks[i](data);
    }
  });
*/
Copy after login

react-router v4 中的代码拆分

最后,回到实际的工作中,基于webpack,在react-router4中实现代码拆分。react-router 4相较于react-router 3有了较大的变动。其中,在代码拆分方面,react-router 4的使用方式也与react-router 3有了较大的差别。

在react-router 3中,可以使用Route组件中getComponent这个API来进行代码拆分。getComponent是异步的,只有在路由匹配时才会调用。但是,在react-router 4中并没有找到这个API,那么如何来进行代码拆分呢?

在react-router 4官网上有一个代码拆分的例子。其中,应用了Bundle Loader来进行按需加载与动态引入

import loadSomething from &#39;bundle-loader?lazy!./Something&#39;
Copy after login

然而,在项目中使用类似的方式后,出现了这样的警告:

Unexpected '!' in 'bundle-loader?lazy!./component/chat'. Do not use import syntax to configure webpack loaders import/no-webpack-loader-syntax
Search for the keywords to learn more about each error.

在webpack 2中已经不能使用import这样的方式来引入loader了(no-webpack-loader-syntax)

Webpack allows specifying the loaders to use in the import source string using a special syntax like this:

var moduleWithOneLoader = require("my-loader!./my-awesome-module");
Copy after login

This syntax is non-standard, so it couples the code to Webpack. The recommended way to specify Webpack loader configuration is in a Webpack configuration file.

我的应用使用了create-react-app作为脚手架,屏蔽了webpack的一些配置。当然,也可以通过运行npm run eject使其暴露webpack等配置文件。然而,是否可以用其他方法呢?当然。

这里就可以使用之前说到的两种方式来处理:import()或require.ensure()。

和官方实例类似,我们首先需要一个异步加载的包装组件Bundle。Bundle的主要功能就是接收一个组件异步加载的方法,并返回相应的react组件:

export default class Bundle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mod: null
    };
  }
  componentWillMount() {
    this.load(this.props)
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.load !== this.props.load) {
      this.load(nextProps)
    }
  }
  load(props) {
    this.setState({
      mod: null
    });
    props.load((mod) => {
      this.setState({
        mod: mod.default ? mod.default : mod
      });
    });
  }
  render() {
    return this.state.mod ? this.props.children(this.state.mod) : null;
  }
}
Copy after login

在原有的例子中,通过Bundle Loader来引入模块:

import loadSomething from 'bundle-loader?lazy!./About'
const About = (props) => (
  <Bundle load={loadAbout}>
    {(About) => <About {...props}/>}
  </Bundle>
)
Copy after login

由于不再使用Bundle Loader,我们可以使用import()对该段代码进行改写:

const Chat = (props) => (
  <Bundle load={() => import('./component/chat')}>
    {(Chat) => <Chat {...props}/>}
  </Bundle>
);
Copy after login

需要注意的是,由于import()会返回一个Promise对象,因此Bundle组件中的代码也需要相应进行调整

export default class Bundle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mod: null
    };
  }
  componentWillMount() {
    this.load(this.props)
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.load !== this.props.load) {
      this.load(nextProps)
    }
  }
  load(props) {
    this.setState({
      mod: null
    });
    //注意这里,使用Promise对象; mod.default导出默认
    props.load().then((mod) => {
      this.setState({
        mod: mod.default ? mod.default : mod
      });
    });
  }
  render() {
    return this.state.mod ? this.props.children(this.state.mod) : null;
  }
}
Copy after login

路由部分没有变化

<Route path="/chat" component={Chat}/>
Copy after login

这时候,执行npm run start,可以看到在载入最初的页面时加载的资源如下

而当点击触发到/chat路径时,可以看到

动态加载了2.chunk.js这个js文件,如果打开这个文件查看,就可以发现这个就是我们刚才动态import()进来的模块。

当然,除了使用import()仍然可以使用require.ensure()来进行模块的异步加载。相关示例代码如下:

const Chat = (props) => (
  <Bundle load={(cb) => {
    require.ensure([], require => {
      cb(require('./component/chat'));
    });
  }}>
  {(Chat) => <Chat {...props}/>}
 </Bundle>
);
Copy after login
export default class Bundle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mod: null
    };
  }
  load = props => {
    this.setState({
      mod: null
    });
    props.load(mod => {
      this.setState({
        mod: mod ? mod : null
      });
    });
  }
  componentWillMount() {
    this.load(this.props);
  }
  render() {
    return this.state.mod ? this.props.children(this.state.mod) : null
  }
}
Copy after login

此外,如果是直接使用webpack config的话,也可以进行如下配置

output: {
  // The build folder.
  path: paths.appBuild,
  // There will be one main bundle, and one file per asynchronous chunk.
  filename: 'static/js/[name].[chunkhash:8].js',
  chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
 },
Copy after login

结束

代码拆分在单页应用中非常常见,对于提高单页应用的性能与体验具有一定的帮助。我们通过将第一次访问应用时,并不需要的模块拆分出来,通过scipt标签动态加载的原理,可以实现有效的代码拆分。在实际项目中,使用webpack中的import()、require.ensure()或者一些loader(例如Bundle Loader)来做代码拆分与组件按需加载。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue.js怎样操作移动数组位置并且更新视图

在Vue中使用vue2-highcharts的图文详解

The above is the detailed content of How to split code based on webpack. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template