我常规的引用外部JS文件是
在es2015中,并不需要这样。我们使用import…from语法
示例:我们在ui.js里定义2个变量
let name = "jack";
let age = 18;
exprot{name,age}; //导出这2个变量
然后在index.js引入:
import{name,age} from "./ui.js";
console.log(name);
然后我们”编译”index.js:
$ babel ./es2015/index.js --out-file ./es2015/index-build.js
编译之后的index-build.js:
"use strict";
var _ui = require("./ui.js");
console.log(_ui.name);
这时我们发现
babel把引用部分编译成了require,而require在我们当前的es5中不能运行的。
这时我们就要安装一个新工具webpack(最火的一款模块加载器简打包工具,它能把各种资源,例如js含”JSX”、coffee、样式含”less/sass”、图片等)
如何安装webpack?
$ sudo npm install -g webpack
我们用nodejs的语法重写ui.js
var name = "jack";
exports.abc = name;
在index.js里:
var m = require("./ui.js");
console.log(m.abc);
nodejs是无法在浏览器运行的,所以我们就要借助webpack来打包一下:
$ webpack ./es2015/index.js ./es2015/index-webpack.js
我们在浏览器测试,控制器打印了”jack”,html代码:
<!DOCTYPE html>
<html>
<head>
<title>es2105的写法</title>
<script type="text/javascript" src="es2015/index-webpack.js"></script>
</head>
<body>
</body>
</html>
webpack打包之后的index-webpack.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] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = 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;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var m = __webpack_require__(1);
console.log(m.abc);
/***/ },
/* 1 */
/***/ function(module, exports) {
var name = "jack";
exports.abc = name;
/***/ }
/******/ ]);