简体   繁体   中英

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. I want the files inside my libs to also be bundled together into that same js file. Here is my folder structure inside my js folder:

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

And here is my gulpfile where I'm bundling them all together:

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 ?

you should be able to call b.require(path) multiple times. (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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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