0

我一直试图将我的代码分成几个文件,然后用 babel 编译并合并到一个文件中一段时间​​。

我有两个文件,functions.js 和 main.js

functions.js 看起来像:

//distance between two points
const distance = (p1, p2) => Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow((p2.y - p1.y), 2));

//slope of line through p1, p2
const slope = (p1, p2) => (p2.x - p1.x) / (p2.y - p1.y);

//etc.

那么main.js中的代码就需要用到这些函数。我的 gulpfile 看起来像:

'use strict';

var projectname = 'canvas-test',
  template_path = '',
  scss_path = template_path + 'scss/**/*.scss',
  es2015_path = template_path + 'es2015/**/*.js',
  scripts_path = template_path + 'scripts/',
  gulp = require('gulp'),
  watch = require('gulp-watch'),
  babel = require('gulp-babel'),
  livereload = require('gulp-livereload'),
  concat = require('gulp-concat');

//Put all javascript tasks here
gulp.task('js', function() {
  return gulp.src(es2015_path + '/**/*.js')
    .pipe(concat('main.js'))
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(gulp.dest(scripts_path))
    .pipe(livereload());
});

//default task
gulp.task('default', ['js'], function() {
  livereload.listen();
  gulp.watch(es2015_path, ['js']);
});

文件 ./scripts/main.js 已成功编译、连接和创建,但是我无法使用这些函数,因为它们被包装在 babel 添加的混乱闭包中:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

///COMPILED CODE FROM FUNCTIONS.JS HERE


},{}],2:[function(require,module,exports){
'use strict';

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

//COMPILED CODE FROM MAIN.JS HERE


},{"./functions.js":1}]},{},[2]);

我花了很长时间寻找解决方案,尝试使用 bBrowserify 和其他一些东西,但无济于事。有什么简单的方法可以做到这一点吗?

4

1 回答 1

0

抱歉,如果这很明显,您是否尝试过交换 babel 转换的顺序?

我记得在babel之前调用concat有一些愚蠢的行为。我通常将 babel 导入,然后 concat/uglify/rename 等。

于 2016-01-24T08:06:00.073 回答