import在webpack5中被编译成什么

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

import被webpack编译成了什么?


提示:以下是本篇文章正文内容,下面案例可供参考

一、WebPack版本

webpack 5

二、步骤

1.三个文件

index.js

/**
 * 入口文件,引入 print 方法,并执行
 * 定义了一个 button 方法,为页面添加一个按钮,并为按钮设置了一个 onclick 事件,负责动态引入一个文件
 */
import { print } from './num.js'

print()

function button () {
  const button = document.createElement('button')
  const text = document.createTextNode('click me')
  button.appendChild(text)
  button.onclick = e => import('./info.js').then(res => {
    console.log(res.log)
  })
  return button
}

document.body.appendChild(button())

info.js

export const log = "log info"

num.js

import { tmpPrint } from './tmp.js'
export function print () {
  tmpPrint() 
  console.log('我是 num.js 的 print 方法')
}

tmp.js

export function tmpPrint () {
  console.log('tmp.js print')
}

2.打包

运行命令npx webpack,mode为development,dist文件夹新建index.html,引入打包后的main.js
在这里插入图片描述
生成两个文件,一个main.js,一个
src_info_js.main.js
在这里插入图片描述

当我们点击按钮时,network中请求src_info_js.main.js文件,就是懒加载机制。然后我们格式化这个文件。
src_info_js.main.js代码如下:

(self["webpackChunkwebpack_bundle_analysis"] =
  self["webpackChunkwebpack_bundle_analysis"] || []).push([
    ["src_info_js"],
    {
    /***/ "./src/info.js":
      /*!*********************!*\
  !*** ./src/info.js ***!
  \*********************/
      /***/ (
      __unused_webpack_module,
      __webpack_exports__,
      __webpack_require__
    ) => {
          eval(
            '__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   "log": () => (/* binding */ log)\n/* harmony export */ });\n/*\r\n * @Author: chenhaoyue\r\n * @Date: 2022-06-21 15:08:05\r\n * @LastEditTime: 2022-06-21 15:08:05\r\n */\r\nconst log = "log info"\n\n//# sourceURL=webpack://webpack-bundle-analysis/./src/info.js?'
          );

          /***/
        },
    },
  ]);

window对象上新增一个webpackChunkwebpack_bundle_analysis属性,类型是数组,向这个数组中push一个数组,index为0的位置是[‘src_info_js’],index为1的位置是一个对象,如下
在这里插入图片描述
eval()函数会将传入的字符串当做javascrit代码来执行,这个函数里面就包含了我们懒加载的info.js代码


可以尝试吧devtool改为false看看打包后的代码

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值