【问题标题】:Browserify: Exported function not found after bundling BootstrapBrowserify:捆绑Bootstrap后找不到导出的功能
【发布时间】:2019-06-07 08:43:28
【问题描述】:

我正在使用 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>

Gulp 文件:

几乎取自Gulp Browserify recipe。您可以看到我已将 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'));
}

【问题讨论】:

    标签: javascript gulp browserify


    【解决方案1】:

    嗯,将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 选项来避免导入脚本中未明确要求的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多