Browserify: экспортированная функция не найдена после объединения Bootstrap - PullRequest
0 голосов
/ 12 января 2019

Я использую Browserify для создания пакета, который содержит экспортированную функцию, которую я хочу вызвать в теге <script>. Все работает нормально, пока я require Bootstrap, после чего функция больше не доступна, и я получаю ошибку:

TypeError: mainBundle.greeting не является функцией

Вот код:

JavaScript ( main.js ):

window.jQuery = require('jquery');
window.$ = global.jQuery;

module.exports = {
  greeting
};

function greeting (name) {
  return `Hello ${name}!`;
}

HTML

<script src="js/bundle.js"></script>
<script>
  // Update greeting
  $('#greeting').text(mainBundle.greeting('Foo'));
</script>

Gulpfile:

В значительной степени взято из рецепта Gulp Browserify . Вы можете видеть, что я добавил опцию standalone в customOpts, чтобы создать автономный модуль, а также require, чтобы добавить Bootstrap. Эта проблема возникает, когда строка require комментируется.

const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const concat = require('gulp-concat');
const watchify = require('watchify');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const log = require('gulplog');

// add custom browserify options here
const customOpts = {
  entries: ['./src/js/main.js'],
  // require: ['bootstrap', 'jquery'],  // UNCOMMENT CAUSES ISSUE
  standalone: 'mainBundle',
  debug: true
};
const opts = {...watchify.args, ...customOpts};
const b = watchify(browserify(opts));
console.log('Browserify options: ', opts);

// add transformations here
// i.e. b.transform(coffeeify);

exports.js = bundle; // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', log.info); // output build logs to terminal

function bundle() {
  return b.bundle()
  // log errors if they happen
    .on('error', log.error.bind(log, 'Browserify Error'))
    .pipe(source('bundle.js'))
    // optional, remove if you don't need to buffer file contents
    .pipe(buffer())
    // optional, remove if you dont want sourcemaps
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
    // Add transformation tasks to the pipeline here.
    .pipe(sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./dist/js'));
}

1 Ответ

0 голосов
/ 12 января 2019

Хм, добавление require в main.js решает проблему:

const bootstrap = require('bootstrap');
window.jQuery = require('jquery');
window.$ = global.jQuery;

module.exports = {
  greeting
};

function greeting (name) {
  return `Hello ${name}!`;
}

Если у кого-нибудь есть лучший ответ, который позволит мне использовать опцию Browserify require, я с радостью приму ваш ответ. Я бы предпочел использовать опцию config, чтобы избежать импорта вещей, которые явно не требуются в моих сценариях.

...