Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

webpack - Javascript: How to create ES5 lib with ES6

I'm working with GoogleAppsScript.
I'm trying to have my code locally in order to:
- use github
- write ES6

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.

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,
   ...
])

But if I copy/paste that code to the javascript of a browser, I'm unable to use the different modules.

If I extract the modules from the bundle and copy/paste to the js console in a browser, this time it works.


I'm sure that webpack/babel can generate the code I need, but I can't find how.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution was to use webpack expose-loader and to move the import/require of the different files to the main.


Here is an example of setup:

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]);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...