How to load component webpack require.ensure in vue
本篇文章主要介绍了vue按需加载组件webpack require.ensure的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
vue-cli是由vue官方发布的快速构建vue单页面的脚手架。
使用 vue-cli构建的项目,在 默认情况下 ,执行 npm run build 会将所有的js代码打包为一个整体,
打包位置是 dist/static/js/app.[contenthash].js
类似下面的路由代码
router/index.js 路由相关信息,该路由文件引入了多个 .vue组件
import Hello from '@/components/Hello' import Province from '@/components/Province' import Segment from '@/components/Segment' import User from '@/components/User' import Loading from '@/components/Loading'
执行 npm run build 会打包为一个整体 app.[contenthash].js ,这个文件是非常大,可能几兆或者几十兆,加载会很慢
所以我们需要分模块打包,把我们想要组合在一起的组件打包到一个 chunk块中去,分模块打包需要下面这样使用 webpack的 require.ensure,并且在最后加入一个 chunk名,相同 chunk名字的模块将会打包到一起。
webpack中利用require.ensure()实现按需加载
1、require.ensure()
webpack 在编译时,会静态地解析代码中的 require.ensure(),同时将模块添加到一个分开的 chunk 当中。这个新的 chunk 会被 webpack 通过 jsonp 来按需加载。
语法如下:
require.ensure(dependencies: String[], callback: function(require), chunkName: String)
依赖 dependencies
这是一个字符串数组,通过这个参数,在所有的回调函数的代码被执行前,我们可以将所有需要用到的模块进行声明。
回调 callback
当所有的依赖都加载完成后,webpack会执行这个回调函数。require 对象的一个实现会作为一个参数传递给这个回调函数。因此,我们可以进一步 require() 依赖和其它模块提供下一步的执行。
chunk名称 chunkName
chunkName 是提供给这个特定的 require.ensure() 的 chunk 的名称。通过提供 require.ensure() 不同执行点相同的名称,我们可以保证所有的依赖都会一起放进相同的 文件束(bundle)。
让我们来看以下的项目
\\ file structure | js --| | |-- entry.js | |-- a.js | |-- b.js webpack.config.js | dist
\\ entry.js require('a'); require.ensure([], function(require){ require('b'); });
\\ a.js console.log('***** I AM a *****');
\\ b.js console.log('***** I AM b *****');
\\ webpack.config.js var path = require('path'); module.exports = function(env) { return { entry: './js/entry.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } } }
通过执行这个项目的 webpack 构建,我们发现 webpack 创建了2个新的文件束, bundle.js 和 0.bundle.js。
entry.js 和 a.js 被打包进 bundle.js.
b.js 被打包进 0.bundle.js.
2、require.ensure() 的坑点
(1)、空数组作为参数
require.ensure([], function(require){ require('./a.js'); });
以上代码保证了拆分点被创建,而且 a.js 被 webpack 分开打包。
(2)、依赖作为参数
require.ensure(['./a.js'], function(require) { require('./b.js'); });
上面代码, a.js 和 b.js 都被打包到一起,而且从主文件束中拆分出来。但只有 b.js 的内容被执行。a.js 的内容仅仅是可被使用,但并没有被输出。
想去执行 a.js,我们需要异步地引用它,如 require(‘./a.js'),让它的 JavaScritp 被执行。
(3)、单独打包成自己写的名字配置
需要配置chunkFilename,和publicPath。publicPath是按需加载单独打包出来的chunk是以publicPath会基准来存放的,chunkFilename:[name].js这样才会最终生成正确的路径和名字
module.exports={ entry:'./js/entry.js', output:{ path:path.resolve(__dirname,"./dist"), filename:'js/a.bundle.js', publicPath:"./", chunkFilename:'js/[name].js' }
所以router/index.js 修改为懒加载组件:
const Province = r => require.ensure([], () => r(require('@/components/Province.vue')), 'chunkname1') const Segment = r => require.ensure([], () => r(require('@/components/Segment.vue')), 'chunkname2') const Loading = r => require.ensure([], () => r(require('@/components/Loading.vue')), 'chunkname3') const User = r => require.ensure([], () => r(require('@/components/User.vue')), 'chunkname3')
根据 chunkame的不同, 上面的四个组件, 将会被分成3个块打包,最终打包之后与组件相关的js文件会分为3个 (除了app.js,manifest.js, vendor.js)
分模块打包之后在 dist目录下是这样的, 这样就把一个大的 js文件分为一个个小的js文件了,按需去下载,其他的使用方法和import的效果一样
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of How to load component webpack require.ensure in vue. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

In Vue.js, lazy loading allows components or resources to be loaded dynamically as needed, reducing initial page loading time and improving performance. The specific implementation method includes using <keep-alive> and <component is> components. It should be noted that lazy loading can cause FOUC (splash screen) issues and should be used only for components that need lazy loading to avoid unnecessary performance overhead.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

Vue component passing values is a mechanism for passing data and information between components. It can be implemented through properties (props) or events: Props: Declare the data to be received in the component and pass the data in the parent component. Events: Use the $emit method to trigger an event and listen to it in the parent component using the v-on directive.

Pagination is a technology that splits large data sets into small pages to improve performance and user experience. In Vue, you can use the following built-in method to paging: Calculate the total number of pages: totalPages() traversal page number: v-for directive to set the current page: currentPage Get the current page data: currentPageData()

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

The render function in Vue.js is an advanced rendering API that allows developers to control the generation of virtual DOMs (VDOMs) through pure JavaScript functions (h functions). The benefits of using the render function include higher performance, greater flexibility, better testability, and compatibility with JSX.
