Javascript:如何使用ES6创建ES5库 [英] Javascript: How to create ES5 lib with ES6
问题描述
我正在使用GoogleAppsScript.
我正在尝试将我的代码本地化,以便:
-使用github
-编写ES6
I'm working with GoogleAppsScript.
I'm trying to have my code locally in order to:
- use github
- write ES6
我正在使用webpack,并且生成将在html页面中运行的包不是问题. But I don't know for now how to generate a bundle that I will be able to copy/paste to GoogleAppsScript.
I'm using webpack, and generating a bundle that will run in a html page is not a problem. But I don't know for now how to generate a bundle that I will be able to copy/paste to GoogleAppsScript.
我创建的 main.js 文件就是这样的:
The main.js file that I create is something like that :
import Point from './Point.js'
import Test from './test.js'
import SpreadSheetLogger from './SpreadSheetLogger.js'
当我查看捆绑包时,我会看到类似的东西:
And when I look to the bundle I have something like that:
/******/ (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__) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _PointJs = __webpack_require__(1);
var _PointJs2 = _interopRequireDefault(_PointJs);
var _testJs = __webpack_require__(2);
var _testJs2 = _interopRequireDefault(_testJs);
var _SpreadSheetLoggerJs = __webpack_require__(4);
var _SpreadSheetLoggerJs2 = _interopRequireDefault(_SpreadSheetLoggerJs);
var a = new _PointJs2['default'](1, 2);
/***/ },
/* 1 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Point = (function () {
function Point(x, y) {
_classCallCheck(this, Point);
this.x = x;
this.y = y;
}
_createClass(Point, [{
key: "toString",
value: function toString() {
return "(" + this.x + ", " + this.y + ")";
}
}]);
return Point;
})();
exports["default"] = Point;
module.exports = exports["default"];
/***/ },
/* 2 */
/***/ function(module, exports) {
"use strict";
[....]
/***/ }
/******/ ]);
所以,如果我看一下摘要,它就像这样:
So if I look summarize, it's something like that:
(function(modules) {
WebPack code
}([
module1,
module2,
...
])
但是,如果我将代码复制/粘贴到浏览器的javascript中,则无法使用其他模块.
But if I copy/paste that code to the javascript of a browser, I'm unable to use the different modules.
如果我从捆绑软件中提取modules
并将copy/paste
提取到浏览器中的js控制台,则这次可以正常工作.
If I extract the modules
from the bundle and copy/paste
to the js console in a browser, this time it works.
我确定webpack/babel可以生成所需的代码,但我找不到方法.
I'm sure that webpack/babel can generate the code I need, but I can't find how.
推荐答案
解决方案是使用webpack expose-loader
并将不同文件的导入/请求移至主文件.
The solution was to use webpack expose-loader
and to move the import/require of the different files to the main.
以下是设置示例:
package.json :
{
"name": "appName",
"version": "0.0.0",
"description": "Code for a google sheet project",
"scripts": {
"watch": "npm install && webpack --watch"
},
"devDependencies": {
"babel-core": "*",
"babel-loader": "*",
"node-libs-browser": "*",
"webpack": "*",
"expose-loader": "*"
}
}
webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './src/main.js',
output: {
path: __dirname + '/out',
filename: 'bundle.js'
},
module: {
loaders: [
{test: path.join(__dirname, 'src'), loader: 'babel-loader'}
]
},
plugins: [
new webpack.NoErrorsPlugin()
],
stats: {
colors: true
}
};
main.js :
require("expose?Test!./Test.js");
// note here that this line replace
// `import {SpreadSheetLogger} from 'SpreadSheetLogger.js'`
// in test.js
require("expose?SpreadSheetLogger!./SpreadSheetLogger.js");
test.js :
// import {SpreadSheetLogger} from 'SpreadSheetLogger.js' is not needed
// as the import is done in the main.js
export default class Test {
runAllTests() {
this.test_logger()
}
test_logger() {
var log = new SpreadSheetLogger()
log.info("This is an info")
}
}
SpreadSheetLogger.js :
export default class SpreadSheetLogger {
constructor() {
this.loggerSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ImportLog");
}
info(data) {
Logger.log(data);
this.loggerSheet.appendRow([new Date(), "INFO", data]);
}
}
这篇关于Javascript:如何使用ES6创建ES5库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!