webpack面试题

194 阅读1分钟

前端为何要进行打包构建?

代码方面

  • 体积更小(Tree-shaking,压缩,合并),加载更快
  • 编译高级语言或语法(Ts,ES6,Scss)
  • 兼容性和错误检查(Polyfill,postcss,eslint)

研发流程方面

  • 统计,高效的开发环境
  • 统一的构建流程和产出标准
  • 集成公司构建规范

chunk/bundle/module的区别?

  • module:各个源码的文件,webpack中一切皆模块
  • chunk: 多模块合并的,如entry,import,splitchunk会生成chunk
  • bundle: 最终的输出文件

loader和plugin的区别?

  • loader:模块转换器
  • plugin:扩展插件

常见的loader和plugin?

babel和webpack的区别?

  • babel-js:语法编译工具,不关心模块化
  • webpack: 模块化打包工具,多个loader,plugin的集合

如何产出一个lib?

  • dllPlugin

babel-polyfill和babel-runtime的区别?

  • polyfill会污染全局,runtime不会

为什么proxy不能实现polyfill?

  • class可以用function模拟
  • proxy不能用Object.defineProperty模拟

webpack优化构建速度

  1. 生产环境
  • 优化babel-loader
  • IgnorePlugin
  • noParse
  • happyPack
  • parallelUglifyPlugin
  1. 开发环境
  • 自动刷新
  • 热更新
  • DllPlugin

webpack优化产出代码

  • 小图片Base64编码
  • bundle加hash
  • 懒加载
  • 提取公共代码
  • 使用CDN加速
  • IgnorePlugin
  • 使用production
  • 使用Scope Hosting
//PWA网站访问一次后会缓存下来,第二次没有开服务器也能访问
workboxplugin -实现PWA插件
//引入
const { GenerateSW } = require('workbox-webpack-plugin');
//plugin
new GenerateSW({
      clientsClaim: true,
      skipWaiting: true
})
//在业务代码中
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js').then(registration => {
      console.log('SW registered: ', registration);
    }).catch(registrationError => {
      console.log('SW registration failed: ', registrationError);
    });
  });
}