分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

webpack与babel解析module.exports差异

发布时间:2023-09-06 02:01责任编辑:蔡小小关键词:webpack
来来来代码先上

js/main.js

import * as aliasPerson from "./person.js";import defaultPerson from "./person.js";console.log("alias person is below ...");console.log(aliasPerson);console.log(aliasPerson.prototype);console.log("default person is below ...");console.log(defaultPerson);console.log(defaultPerson.prototype);


js/person.js

function Person(){}Person.nickname = "this is a person";Person.birthday = "1900-01-01";Person.prototype.eat = function(){};module.exports = Person;


webpack.config.js

var entryFilePath = "./js/main.js";var webpackConfig = {   entry: entryFilePath,   output: {      filename: "result.js"   },   module: {      // rules: [{test: /\.js$/,loader: 'babel-loader'}]    }};module.exports = webpackConfig;


.babelrc

{  "presets": [      "es2015",      "stage-3"    ],    "plugins": [      ["transform-runtime",        {          "helpers": false,          "polyfill": false,          "regenerator": true,          "moduleName": "babel-runtime"        }]    ]}


package.json

{    "scripts": {        "build": "webpack"    },    "devDependencies": {        "babel-core": "^6.26.3",        "babel-loader": "^7.1.4",        "babel-plugin-transform-runtime": "^6.23.0",        "babel-preset-es2015": "^6.24.1",        "babel-preset-stage-3": "^6.24.1",        "babel-runtime": "^6.26.0",        "webpack": "^3.10.0",        "webpack-dev-server": "^2.9.7"    }}


一 不使用babel做转义

直接执行 npm run build 生成result.js

执行 node result.js


import * as aliasPerson from "./person.js";

import defaultPerson from "./person.js";

执行结构完全一样


二 使用babel做转义

取消如下注释.

执行 npm run build 生成result.js

执行 node result.js

使用 import * as aliasPerson from "./person.js";

多了 一个default属性,并且 aliasPerson.prototype 为 undefined


原因如下

import * as aliasPerson from "./person.js";

当引入的 ./person.js 模块不为es 模块的时候(obj.__esModule === false)

babel会将 module.exports 所指向的对象的非继承属性遍历并附加到 newObj对象中,

并且 newObj.default = module.exports


webpack与babel解析module.exports差异

原文地址:http://blog.51cto.com/antlove/2133983

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved