最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to run functions that converted by webpack? - Stack Overflow

programmeradmin1浏览0评论

I have a simple library, and I am working with ES6, and I have some require keyword, then, I need to convert this to a version that browsers understand it, I use webpack to make the browser version of my library.

Here is an example:


main.js

import Test from './test';

function callMe(){
    console.log("I am damn called!");
}

test.js

export default function(string) {
  console.log("This is awesome!");
  [1,2,3].map(n => n + 1);
}

gulpfile.js (I use Gulp)

var gulp = require('gulp');
var babel = require('gulp-babel'); 
gulp.task('babel', () => {
    return gulp.src('src/*.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('dist/babel'));
});


var webpack = require('gulp-webpack');
gulp.task('webpack', function() {
  return gulp.src('dist/babel/main.js')
    .pipe(webpack())
    .pipe(gulp.dest('dist/'));
});

Now when I run the Gulp tasks (babel and webpack), I will get a file which is the result of webpack (and means all require and import are converted now)

Here is the result of webpack (I mean the convert result):

/******/ (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";

	var _test = __webpack_require__(1);

	var _test2 = _interopRequireDefault(_test);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	function callMe() {
		console.log("I am damn called!");
	}

/***/ },
/* 1 */
/***/ function(module, exports) {

	"use strict";

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	exports.default = function (string) {
	  console.log("This is awesome!");
	  [1, 2, 3].map(function (n) {
	    return n + 1;
	  });
	};

/***/ }
/******/ ]);

I have a simple library, and I am working with ES6, and I have some require keyword, then, I need to convert this to a version that browsers understand it, I use webpack to make the browser version of my library.

Here is an example:


main.js

import Test from './test';

function callMe(){
    console.log("I am damn called!");
}

test.js

export default function(string) {
  console.log("This is awesome!");
  [1,2,3].map(n => n + 1);
}

gulpfile.js (I use Gulp)

var gulp = require('gulp');
var babel = require('gulp-babel'); 
gulp.task('babel', () => {
    return gulp.src('src/*.js')
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('dist/babel'));
});


var webpack = require('gulp-webpack');
gulp.task('webpack', function() {
  return gulp.src('dist/babel/main.js')
    .pipe(webpack())
    .pipe(gulp.dest('dist/'));
});

Now when I run the Gulp tasks (babel and webpack), I will get a file which is the result of webpack (and means all require and import are converted now)

Here is the result of webpack (I mean the convert result):

/******/ (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";

	var _test = __webpack_require__(1);

	var _test2 = _interopRequireDefault(_test);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	function callMe() {
		console.log("I am damn called!");
	}

/***/ },
/* 1 */
/***/ function(module, exports) {

	"use strict";

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	exports.default = function (string) {
	  console.log("This is awesome!");
	  [1, 2, 3].map(function (n) {
	    return n + 1;
	  });
	};

/***/ }
/******/ ]);

The first question is, now, how can I execute (and access) the callMe function that defined in main.js and now bundled by webpack?

The other question is that, the code looks ugly and not simple, is there any way to simplify it?

And I also think webpack seems to be something else that just be for converting require to a browser supportable version, and browserify had problems with Gulp. Any suggestion?

Share Improve this question asked Nov 21, 2016 at 13:51 LashLash 831 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

How can I execute (and access) the callMe function that defined in main.js?

You can't, because you didn't export it. You should change your code to something like that:

import Test from './test';

export default function callMe(){
  console.log("I am damn called!");
}

Then you can import it like that:

import callMe from 'dist/main.js';
callMe(); // logs "I am damn called!"

The code looks ugly and not simple, is there any way to simplify it?

There's no need to simplify it. There's nothing wrong with bundled code looking ugly, because anyway it's not going to be read by humans.

Since searching how to expose a function using webpack brought me here and the answer was hidden in the ments I'll post it here to be more visible.

I want the callMe() function to be visible on global (window) object when my webpack-bundeled-script is loaded. In my case I want to invoke delyed bootstrap of my Angular2 app on a button click, but that's just implementation detail.


So in the main.js I export my function:

export function callMe(){
  console.log("I am damn called!");
  // And I do more things ;)
}

And according to the webpack docs, in the webpack.js configuration I do:

module.exports = {
  entry {
    app: "dist/babel/main.js"
  }, 
  output {
    // My funky output configs...

    libraryTarget: "this"

  }
}

That's it. The this refers to the global window object as it is loaded using <script> tag in my html page.

Sorry to the OP, I don't know the Gulp-webpack configuration. But I thing it might work just passing the above object to the webpack() function according to the gulp-webpack docs.

发布评论

评论列表(0)

  1. 暂无评论