代码分离方法有三种:node
webpack v4.6.0+ 添加了预取和预加载的支持。react
在声明 import 时,使用下面这些内置指令,能够让 webpack 输出 "resource hint(资源提示)",来告知浏览器:webpack
splitChunks: { chunks: 'all', // 提取公共模块 loadash // 将第三方库(library)(例如 lodash 或 react)提取到单独的 vendor chunk 文件中,是比较推荐的作法 // 利用 client 的长效缓存机制,命中缓存来消除请求,并减小向 server 获取资源,同时还能保证 client 代码和 server 代码版本一致。 cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'all' } } },
runtimeChunk: 'single' // 提取引导模板 将 runtime 代码拆分为一个单独的 chunk
// filename: '[name].[contenthash].js', // content hash 内容变化才会变化 filename: 'webpack-numbers.js', path: path.resolve(__dirname, 'dist'), // 暴露 library 这是库名称 import from 'webpackNumbers' library: 'webpackNumbers', libraryTarget: 'umd'
const { HashedModuleIdsPlugin } = require('webpack'); plugins: [ // 不会因模块增长和减小致使的模块内容变化,增长长缓存命中机制 new HashedModuleIdsPlugin() ],
分析打包代码浏览器
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer'); plugins: [ new BundleAnalyzerPlugin() ]