Answer the question
In order to leave comments, you need to log in
How to write gulp-task to build modular js with browserify?
Hello.
Please tell me how to write a gulp task to build *.js files from typescript using browserify with the following conditions:
/<project_dir>
/public
/static
/js
/maps
...
/modules
...
common.js
/static
/typescript
/compile
/modules
...
/import
...
Answer the question
In order to leave comments, you need to log in
I asked myself - I will answer. As I understand it, neither browserify nor webpack can specify wildcard as entry points. In my search, I came up with two solutions.
If you solve the problem using browserify, you need to take care of generating a list of files and creating all the necessary directories yourself. You will get something like this:
gulp.task('compile-typescript', function () {
let browserify = require('browserify'),
factor = require('factor-bundle'),
tsify = require('tsify'),
path = require('path'),
source = require('vinyl-source-stream'),
glob = require('glob'),
mkdirp = require('mkdirp'),
srcDir = 'static/typescript/compile/',
distDir = 'public/static/js/',
entries = glob.sync(srcDir + '**/*[email protected](ts|tsx)'),
outputs = [],
mkdirProccess = [],
typescriptOptions = {
module: 'commonjs',
target: 'es5',
jsx: 'React'
};
entries.forEach(function (filename) {
let relativePath = path.dirname(path.relative(srcDir, filename)),
basename = path.basename(filename, path.extname(filename)) + '.js';
if (relativePath === '.') {
relativePath = '';
} else {
relativePath += '/';
mkdirProccess.push(new Promise(function (resolve, reject) {
mkdirp(distDir + relativePath, function (error) {
if (error) reject(error);
else resolve();
});
}));
}
outputs.push(distDir + relativePath + basename);
});
Promise.all(mkdirProccess)
.then(function () {
browserify({
entries,
debug: true
})
.plugin(tsify, typescriptOptions)
.plugin(factor, {
outputs,
threshold: 2
})
.bundle()
.pipe(source('common.js'))
.pipe(gulp.dest(distDir));
});
});
gulp.task('compile-typescript', function () {
let webpack = require('webpack-stream'),
named = require('vinyl-named'),
srcDir = 'static/typescript/compile/',
distDir = 'public/static/js/';
return gulp.src(srcDir + '**/*[email protected](ts|tsx)')
.pipe(named(file => file.relative.replace(/\.tsx?$/, '')))
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest(distDir));
});
'use strict';
const webpack = require('webpack');
module.exports = {
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.js', '.ts', '.tsx']
},
output: {
sourceMapFilename: 'maps/[file].map'
},
module: {
loaders: [
{ test: /\.tsx?$/, loader: 'ts-loader' }
]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'common',
minChunks: 3
})
],
devtool: 'source-map'
};
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"jsx": "React",
"sourceMap": true
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question