简体   繁体   English

如何将lib中的js文件与主app.js捆绑在一起

[英]How can I bundle js files in my lib with main app.js

Right now, only my app.js and the files that I use inside it are being bundled. 现在,仅捆绑了我的app.js和其中使用的文件。 I want the files inside my libs to also be bundled together into that same js file. 我希望我的库中的文件也一起捆绑到相同的js文件中。 Here is my folder structure inside my js folder: 这是我的js文件夹中的文件夹结构:

.
├── app.js
├── components
└── libs
    └── materialize.min.js

And here is my gulpfile where I'm bundling them all together: 这是我的gulpfile,将它们捆绑在一起:

import gulp from 'gulp'
import source from 'vinyl-source-stream'
import buffer from 'vinyl-buffer'
import browserify from 'browserify'
import babelify from 'babelify'
import uglify from 'gulp-uglify'
import watchify from 'watchify'

const jsDirs = {
  src: './client/js/app.js',
  dest: './dist/js'
}

function buildBundle(b) {
  b.bundle()
  .pipe(source('bundle.js'))
  .pipe(gulp.dest(jsDirs.dest))
}

gulp.task('scripts', () => {
  let b = browserify({
    cache: {},
    packageCache: {},
    fullPaths: true
  })
  b = watchify(b.transform(babelify))
  b.on('update', () => buildBundle(b))
  b.add(jsDirs.src)
  buildBundle(b)
})

gulp.task('default', ['scripts'])

Is there any way to include my libs js files which aren't being used by app.js ? 有什么办法可以包含app.js未使用的libs js文件吗?

you should be able to call b.require(path) multiple times. 您应该能够多次调用b.require(path) (that's how I do it for mine) Something like : (这就是我为我做的事情):

import gulp from 'gulp'
import source from 'vinyl-source-stream'
import buffer from 'vinyl-buffer'
import browserify from 'browserify'
import babelify from 'babelify'
import uglify from 'gulp-uglify'
import watchify from 'watchify'

const jsDirs = {
  src: './client/js/app.js',
  dest: './dist/js',
  requires: [
      './libs/materialize.min.js',
      ['./libs/whatever.js', 'whatever']
  ]
}

function buildBundle(b) {
  b.bundle()
  .pipe(source('bundle.js'))
  .pipe(gulp.dest(jsDirs.dest))
}

gulp.task('scripts', () => {
  let b = browserify({
    cache: {},
    packageCache: {},
    fullPaths: true
  });
  b = watchify(b.transform(babelify))
  [].concat(jsDirs.requires || []).forEach(function (req) {
        var path = req,
            expose = null;
        if (typeof path !== 'string') {
            expose = path[1];
            path = path[0]
        }
        b.require(path, expose ? { expose: expose } : {});
  });

  b.on('update', () => buildBundle(b))
  b.add(jsDirs.src)
  buildBundle(b)
})

gulp.task('default', ['scripts'])

this also let you expose the lib for futur requires 这也让您可以将lib暴露给未来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM