BabelJS - 将 ES6 模块转换为 ES5

在本文中,我们将看到如何使用 Babel 将 ES6 模块转换为 ES5。
Modules
考虑需要重用部分 JavaScript 代码的场景。 ES6 用模块的概念来拯救你。
一个模块只不过是写在一个文件中的一段 JavaScript 代码。模块中的函数或变量不可用,除非模块文件导出它们。
简单来说,这些模块帮助您在模块中编写代码,并且只公开应该由代码的其他部分访问的那些代码部分。
让我们考虑一个示例来了解如何使用模块以及如何导出它以在代码中使用它。
举个例子
add.js
var add = (x,y) => {
return x+y;
}
module.exports=add;
multiply.js
var multiply = (x,y) => {
return x*y;
};
module.exports = multiply;
main.js
import add from './add';
import multiply from './multiply'
let a = add(10,20);
let b = multiply(40,10);
console.log("%c"+a,"font-size:30px;color:green;");
console.log("%c"+b,"font-size:30px;color:green;");
我有三个文件 add.js 添加 2 个给定数字,multiply.js 将两个给定数字相乘,main.js 调用 add 和 multiply,并控制输出。
给main.js中的add.js和multiply.js,我们要先导出,如下
module.exports = add;
module.exports = multiply;
要在 main.js 中使用它们,我们需要导入它们,如下所示
import add from './add';
import multiply from './multiply'
我们需要模块捆绑器来构建文件,以便我们可以在浏览器中执行它们。
我们可以做到 -
使用 Webpack
使用 Gulp
ES6 模块和 Webpack
在本节中,我们将了解 ES6 模块是什么。我们还将学习如何使用 webpack。
在开始之前,我们需要安装以下包
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-env
package.json
{
"name": "babelwebpack",
"version": "1.0.0",
"description": "babel webpack ingegraty",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"pack": "webpack",
"publish": "webpack-dev-server --output-public-path=/dev/"
},
"keywords": [
"babel",
"webpack"
],
"author": "hk",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.18.10",
"@babel/core": "^7.18.13",
"@babel/preset-env": "^7.18.10",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.10.1"
},
"dependencies": {
"babel-loader": "^8.2.5"
}
}
我们已将打包和发布任务添加到脚本以使用 npm 运行它们。这是构建最终文件的 webpack.config.js 文件。
webpack.config.js
var path = require('path');
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: path.resolve(__dirname, 'dev'),
filename: 'main_bundle.js'
},
mode:'development',
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
query: {
presets: ['env']
}
}
]
}
};
运行命令 npm run pack 来构建文件。最终文件将存储在 dev/ 文件夹中。
dev/main_bundle.js
通用文件被创建。该文件结合了 add.js、multiply.js 和 main.js
并将其存储在 dev/main_bundle.js
中。
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string')
for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
};
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/main.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./src/add.js":
/*!********************!*\
!*** ./src/add.js ***!
\********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval(
"\n\nvar add = function add(x, y) {\n return x + y;\n};
\n\nmodule.exports = add;
\n\n//# sourceURL = webpack:///./src/add.js?"
);
/***/ }),
/***/ "./src/main.js":
/*!*********************!*\
!*** ./src/main.js ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval(
"\n\nvar _add = __webpack_require__(/*! ./add */ \"./src/add.js\");
\n\nvar _add2 = _interopRequireDefault(_add);
\n\nvar _multiply = __webpack_require__(/*! ./multiply */ \"./src/multiply.js\");
\n\nvar _multiply2 = _interopRequireDefault(_multiply);
\n\nfunction _interopRequireDefault(obj) {
return obj >> obj.__esModule ? obj : { default: obj };
}
\n\nvar a = (0, _add2.default)(10, 20);
\nvar b = (0, _multiply2.default)(40, 10);
\n\nconsole.log(\"%c\" + a, \"font-size:30px;color:green;\");
\nconsole.log(\"%c\" + b, \"font-size:30px;color:green;\");
\n\n//# sourceURL = webpack:///./src/main.js?"
);
/***/ }),
/***/ "./src/multiply.js":
/*!*************************!*\
!*** ./src/multiply.js ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval(
"\n\nvar multiply = function multiply(x, y) {\n return x * y;\n};
\n\nmodule.exports = multiply;
\n\n//# sourceURL = webpack:///./src/multiply.js?"
);
/***/ })
/******/ });
以下是在浏览器中测试输出的命令
npm run publish
在您的项目中添加 index.html。这会调用 dev/main_bundle.js。
<html>
<head></head>
<body>
<div>public path</div>
<script type="text/javascript" src="dev/main_bundle.js"></script>
</body>
</html>
输出如下:
