I'm still a beginner, i try to to export and import one class into a main file, the other class in the others class file and use them.
And then gulp ES5 code with 6to5 (now Babel).
// file a.js
import B from 'b.js';
class A {
constructor() {
B.methodB();
}
}
export default A;
// file b.js
class B {
methodB() {
console.log('hi from b');
}
}
export default B;
// file main.js
import A from 'a.js';
new A();
My gulpfile:
var gulp = require('gulp');
var to5 = require('gulp-6to5');
gulp.task('default', function () {
return gulp.src('main.js')
.pipe(to5())
.pipe(gulp.dest('dist'));
});
And this is my dist/main.js file:
"use strict";
var _interopRequire = function (obj) {
return obj && (obj["default"] || obj);
};
var A = _interopRequire(require("a.js"));
new A();
The error in console: ReferenceError: require is not defined
Which of course does not work ... what am I doing wrong or what lack I yet? I do not get it exactly.
I was having the exact same problem before myself... As Qantas mentioned in the comments, Babel (formerly 6to5) will convert syntax, but it won't do module loading or polyfills.
I've found the easiest workflow is using browserify with gulp. This takes care of transpiling, adding polyfills, bundling, minification, and source map generation in one hit. This question has a pretty nice example: Gulp + browserify + 6to5 + source maps.
This version adds minification and polyfills. An example for your case would look like this:
let gulp = require('gulp');
let browserify = require('browserify');
let babelify = require('babelify');
let util = require('gulp-util');
let buffer = require('vinyl-buffer');
let source = require('vinyl-source-stream');
let uglify = require('gulp-uglify');
let sourcemaps = require('gulp-sourcemaps');
gulp.task('build:demo', () => {
browserify('./demo/app.js', { debug: true })
.add(require.resolve('babel-polyfill/dist/polyfill.min.js'))
.transform(babelify.configure({ presets: ['es2015', 'es2016', 'stage-0', 'stage-3'] }))
.bundle()
.on('error', util.log.bind(util, 'Browserify Error'))
.pipe(source('demo.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(uglify({ mangle: false }))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./demo'));
});
gulp.task('default', ['build:demo']);
It's important that uglify has mangle set to false; it really doesn't seem to play nice with the transformed code.
If you don't have all the dependencies installed, you may want to create a package.json file, and ensure that following packages are defined in the dependencies object:
"devDependencies": {
"babel-polyfill": "^6.13.0",
"babel-preset-es2015": "^6.13.0",
"babel-preset-es2016": "^6.11.0",
"babel-preset-stage-0": "^6.5.0",
"babel-preset-stage-3": "^6.11.0",
"babelify": "^7.3.0",
"browserify": "^13.1.0",
"gulp": "^3.9.0",
"gulp-sourcemaps": "^1.6.0",
"gulp-uglify": "^2.0.0",
"gulp-util": "^3.0.0",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
}
Most of these won't work if installed with -g, so consider yourself warned :P
Then, just run npm install to install all the dependencies, and gulp to run the default task and transpile all of your code.
Your other files look good, you have the right idea with importing at the beginning of each file and exporting your defaults :) If you want some examples of babelified ES6 in the wild, I have a couple of projects on GitHub that might help.
It's seems you need to import the requirejs fond in your HTML like that:
<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.15/require.min.js"></script>
And your files need to be something like that:
// file a.js
import B from './b';
class A {
constructor() {
B.methodB = function() {
};
}
}
export default A;
// file b.js
class B {
methodB() {
console.log('hi from b');
}
}
export default B;
// main.js
import A from './a';
new A();
Note that you need to put the module's directory ./a and ./b on the import.
And your gulpfile need to be:
var gulp = require('gulp');
var to5 = require('gulp-6to5');
gulp.task('default', function () {
return gulp.src('src/*.js')
.pipe(to5())
.pipe(gulp.dest('dist'));
});
Note that you need to transform all of your file with src/*.js on the gulp.src
Related
I've got a JS project where I'm trying to use async/await, I've installed the relevant package to transform runtime, but still get this error:
regeneratorRuntime is not defined
What am I missing?
package.json
"dependencies": {
"#babel/core": "^7.14.0",
"#babel/plugin-transform-runtime": "^7.13.15",
"#babel/preset-env": "^7.14.1",
"bootstrap": "4.6.0",
"eslint": "7.21.*",
"gulp": "4.0.2",
"gulp-autoprefixer": "7.0.*",
"gulp-babel": "^8.0.0",
"gulp-concat": "2.6.*",
"gulp-eslint": "6.0.*",
"gulp-minify": "3.1.*",
"gulp-sass": "4.1.*",
"gulp-stylelint": "13.0.*",
"stylelint": "13.11.*"
},
gulpfile.js
const gulp = require('gulp')
const sass = require('gulp-sass')
const babel = require('gulp-babel')
const concat = require('gulp-concat')
const minify = require('gulp-minify')
const eslint = require('gulp-eslint')
const autoprefixer = require('gulp-autoprefixer')
// build the JS
gulp.task('build-js', () =>
gulp.src([
'src/js/plugins/input.js'
])
.pipe(concat('output.js'))
.pipe(babel({
presets: [['#babel/env', { modules: false }]]
}))
.pipe(minify())
.pipe(gulp.dest('src/assets/js/'))
);
I was having the same problem. The solution was to concatenate the output.js file with the file node_modules/regenerator-runtime/runtime.js. Basically you just need to have this file being loaded somewhere in your website.
I didn't find the need for #babel/plugin-transform-runtime, but I am still understanding how all of this works, so let me know if it is necessary.
Here's a possible gulpfile.js:
'use strict';
// Import `src` and `dest` from gulp for use in the task.
const { series, parallel, src, dest } = require("gulp")
// Import Gulp plugins.
// CSS related
const sass = require('gulp-sass')(require('sass')); // compile scss to css
const autoprefixer = require('gulp-autoprefixer'); // add vendor prefixes to css for older browsers
const cleanCSS = require('gulp-clean-css'); // minify css
// JS related
const babel = require("gulp-babel"); // compile JS for older browsers
const uglify = require("gulp-uglify"); // minify JS
const concat = require("gulp-concat"); // concatenate files
const del = require("del"); // delete files
const plumber = require("gulp-plumber"); // Stop at gulp errors
const destDir = './dist';
const paths = {
styles: {
src: './sass/**/*.scss',
dest: `${destDir}/css/`,
bundleName: `main.css`
},
scripts: {
src: './js/**/*.js',
dest: `${destDir}/js/`,
bundleName: `main.js`
}
};
function clean() {
return del([paths.styles.dest, paths.scripts.dest])
}
function delTemp() {
return del([tempDir]);
}
function jsDeps() {
const files = [
"node_modules/regenerator-runtime/runtime.js"
]
return (
src(files)
.pipe(plumber())
// Combine these files into a single main.deps.js file.
.pipe(concat("main.deps.js"))
.pipe(uglify())
// Save the concatenated file to the tmp directory.
.pipe(dest(tempDir))
)
}
function jsBuild() {
// This will grab any file within js/ or its
// subdirectories, then ...
return src(paths.scripts.src)
// Stop the process if an error is thrown.
.pipe(plumber())
// Concatenate all files within src/components and its
// subdirectories into a single file named main.js.
.pipe(concat("main.build.js"))
// Transpile the JS code using Babel's preset-env.
.pipe(
babel({
presets: [
[
"#babel/env",
{
modules: false
}
]
]
})
)
// Minify the self-authored bundle.
.pipe(uglify())
// Save each component as a separate file in dist.
.pipe(dest(tempDir));
}
function jsConcat(done) {
// An array of the two temp (concatenated) files.
const files = [`${tempDir}/main.deps.js`, `${tempDir}/main.build.js`]
return (
src(files)
.pipe(plumber())
// Concatenate the third-party libraries and our
// homegrown components into a single main.js file.
.pipe(concat(paths.scripts.bundleName))
// Save it to the final destination.
.pipe(dest(paths.scripts.dest))
)
}
function sassBuild() {
return src(paths.styles.src)
.pipe(plumber())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
cascade: false
}))
.pipe(concat(paths.styles.bundleName))
.pipe(cleanCSS())
.pipe(dest(paths.styles.dest));
}
const build = series(clean, parallel(series(jsDeps, jsBuild, jsConcat), sassBuild), delTemp);
/*
* You can use CommonJS `exports` module notation to declare tasks
*/
exports.clean = clean;
exports.sassBuild = sassBuild;
exports.jsBuild = jsBuild;
exports.build = build;
// Gulp 4 uses exported objects as its tasks. Here we only have a
// single export that represents the default gulp task.
exports.default = build;
Current project handle babel and gulp for task and load a yml config file for paths.
This is the cofing.yml:
PATHS:
# Path to source folder
sources: "jet/static/jet_src"
# Path to dist folder
dist: "jet/static/jet"
# Paths to static assets that aren't images, CSS, or JavaScript
assets:
- "jet/static/jet_src/**/*"
- "!jet/static/jet_src/{img,js,scss,fonts}/**/*"
# Paths to fonts folder
fonts:
- "jet/static/jet_src/fonts/**/*"
- "node_modules/font-awesome/fonts/**/*"
# Paths to Sass libraries, which can then be loaded with #import
sass:
- "jet/static/jet_src/scss"
- "jet/static/jet_src/scss/select2"
- "node_modules/font-awesome/scss/"
- "node_modules/select2/src/scss/"
- "node_modules/perfect-scrollbar/src/scss/"
# Paths to JavaScript libraries, which are compined into one file
javascript:
- "jet/static/jet_src/js/!(main).js"
- "jet/static/jet_src/js/main.js"
- "jet/static/jet_src/js/!(select2.jet).js"
- "jet/static/jet_src/js/select2.jet.js"
libraries:
- "node_modules/jquery/dist/jquery.js"
# - "node_modules/jquery-ui/jquery-ui.js"
- "node_modules/select2/dist/js/select2.full.js"
- "node_modules/perfect-scrollbar/dist/js/perfect-scrollbar.js"
- "node_modules/perfect-scrollbar/dist/js/perfect-scrollbar.jquery.js"
- "node_modules/js-cookie/src/js.cookie.js"
This is the gulpfile.babel.js:
'use strict';
import plugins from 'gulp-load-plugins';
import yargs from 'yargs';
import browser from 'browser-sync';
import merge from 'merge-stream';
import gulp from 'gulp';
// import panini from 'panini';
import rimraf from 'rimraf';
// import sherpa from 'style-sherpa';
import yaml from 'js-yaml';
import fs from 'fs';
import path from 'path';
// Themes path
const themesPath = "jet/static/jet_src/scss/themes/";
// Load all Gulp plugins into one variable
const $ = plugins();
// Check for --production flag
const PRODUCTION = !!(yargs.argv.production);
// Load settings from settings.yml
const {COMPATIBILITY, PORT, UNCSS_OPTIONS, PATHS} = loadConfig();
function loadConfig() {
let ymlFile = fs.readFileSync('config.yml', 'utf8');
return yaml.load(ymlFile);
}
function getFolders(dir) {
return fs.readdirSync(dir)
.filter(function (file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
// Build the "dist" folder by running all of the below tasks
gulp.task('build', gulp.series(clean, gulp.parallel(sass, javascript, images, fonts)));
// Build the site, run the server, and watch for file changes
gulp.task('default', gulp.series('build', server, watch));
// Delete the "dist" folder
// This happens every time a build starts
function clean(done) {
rimraf(PATHS.dist, done);
}
// Compile Sass into CSS
// In production, the CSS is compressed
function sass() {
var folders = getFolders(themesPath);
return folders.map(folder => {
gulp.src(path.join(themesPath, folder, '/**/*.scss'))
.pipe($.sourcemaps.init())
.pipe($.sass({
includePaths: PATHS.sass
})
.on('error', $.sass.logError))
.pipe($.autoprefixer({
browsers: COMPATIBILITY
}))
// Comment in the pipe below to run UnCSS in production
.pipe($.if(PRODUCTION, $.uncss(UNCSS_OPTIONS)))
.pipe($.if(PRODUCTION, $.cssnano()))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest(PATHS.dist + '/css/themes/' + folder))
.pipe(browser.reload({stream: true}));
});
}
// Combine JavaScript into one file
// In production, the file is minified
function javascript() {
var js = gulp.src(PATHS.javascript)
.pipe($.sourcemaps.init())
.pipe($.babel())
.pipe($.concat('main.js'))
.pipe($.if(PRODUCTION, $.uglify()
.on('error', e => {
console.log(e);
})
))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest(PATHS.dist + '/js'));
var libs = gulp.src(PATHS.libraries)
.pipe($.sourcemaps.init())
.pipe($.babel())
.pipe($.concat('libraries.js'))
.pipe($.if(PRODUCTION, $.uglify()
.on('error', e => {
console.log(e);
})
))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest(PATHS.dist + '/js'));
return merge(js, libs);
}
// Copy images to the "dist" folder
// In production, the images are compressed
function images() {
return gulp.src(PATHS.sources + '/img/**/*')
.pipe($.if(PRODUCTION, $.imagemin({
progressive: true
})))
.pipe(gulp.dest(PATHS.dist + '/img'));
}
// Copy fonts to the "dist" folder
function fonts() {
return gulp.src(PATHS.fonts)
.pipe(gulp.dest(PATHS.dist + '/fonts'));
}
// Start a server with BrowserSync to preview the site in
function server(done) {
browser.init({
server: PATHS.dist, port: PORT
});
done();
}
// Reload the browser with BrowserSync
function reload(done) {
browser.reload();
done();
}
// Watch for changes to static assets, Sass, and JavaScript
function watch() {
gulp.watch(PATHS.sources + '/scss/**/*.scss', sass);
gulp.watch(PATHS.sources + '/js/**/*.js').on('change', gulp.series(javascript, browser.reload));
gulp.watch(PATHS.sources + '/img/**/*').on('change', gulp.series(images, browser.reload));
gulp.watch(PATHS.sources + '/fonts/**/*').on('change', gulp.series(fonts, browser.reload));
}
In single view this files haven't problems, but, when exute gulp command i have the next error in console:
npm start ✓ 1949 10:49:29
> django-jetpack#1.0.0-b start /Users/jose/Proyectos/django-jetpack
> gulp
[10:49:35] Requiring external module babel-register
[10:49:40] Using gulpfile ~/Proyectos/django-jetpack/gulpfile.babel.js
[10:49:40] Starting 'default'...
[10:49:40] Starting 'build'...
[10:49:40] Starting 'clean'...
[10:49:40] Finished 'clean' after 3.23 ms
[10:49:40] Starting 'sass'...
[10:49:40] Starting 'javascript'...
[10:49:40] Starting 'images'...
[10:49:40] Starting 'fonts'...
[10:49:46] Finished 'images' after 5.91 s
[BABEL] Note: The code generator has deoptimised the styling of "/Users/jose/Proyectos/django-jetpack/node_modules/jquery/dist/jquery.js" as it exceeds the max of "100KB".
[BABEL] Note: The code generator has deoptimised the styling of "/Users/jose/Proyectos/django-jetpack/node_modules/select2/dist/js/select2.full.js" as it exceeds the max of "100KB".
[10:49:57] Finished 'javascript' after 16 s
[10:49:57] Finished 'fonts' after 16 s
[10:49:57] The following tasks did not complete: default, build, <parallel>, sass
[10:49:57] Did you forget to signal async completion?
The npminstalled packages are:
"devDependencies": {
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"babel-register": "^6.9.0",
"browser-sync": "^2.13.0",
"font-awesome": "^4.6.3",
"gulp": "github:gulpjs/gulp#4.0",
"gulp-autoprefixer": "^3.1.0",
"gulp-babel": "^6.1.2",
"gulp-cli": "^1.2.1",
"gulp-concat": "^2.6.0",
"gulp-cssnano": "^2.1.2",
"gulp-extname": "^0.2.2",
"gulp-if": "^2.0.1",
"gulp-imagemin": "^3.0.1",
"gulp-load-plugins": "^1.2.4",
"gulp-sass": "^2.3.2",
"gulp-sourcemaps": "^1.6.0",
"gulp-uglify": "^1.5.3",
"gulp-uncss": "^1.0.5",
"jquery": "^3.0.0",
"js-cookie": "^2.1.2",
"js-yaml": "^3.6.1",
"merge-stream": "^1.0.0",
"node-sass": "^3.8.0",
"perfect-scrollbar": "^0.6.11",
"rimraf": "^2.5.2",
"select2": "^4.0.3",
"susy": "^2.2.12",
"yargs": "^4.7.1"
}
This setting was taked from Zurb Foundation Template and it works fine, so, we think that have to works fine, but isn't.
I don't understand why i have this problem because all task are in series function, sasstask works fine, compile all scss files, javascripttask join all js scripts in main.jsand libraries.jsfiles, so, i think that this task are good defined, but, what happen with the other task?
From the other answer I already linked:
Since your task could contain asynchronous code you have to signal Gulp when your task has finished executing.
In Gulp 3.x you could get away without doing this. Gulp would just assume that your task is synchronous and that it has finished as soon as your task function returns. Gulp 4.x seems to be stricter in this regard. You have to signal task completion.
You can do that in three ways:
Return a Stream.
Return a Promise.
Call the callback function.
Look at the sass task in the Zurb Foundation Template that you based your code on. It uses the first mechanism to signal async completion: returning a stream.
You've changed that task. It no longer returns a stream. It returns an array. That's why your sass task fails.
So you need return a stream in your sass task. One way to do this would be to merge the different streams into one single stream using merge-stream:
var merge = require('merge-stream');
function sass() {
var folders = getFolders(themesPath);
return merge.apply(null, folders.map(folder => {
return gulp.src(path.join(themesPath, folder, '/**/*.scss'))
.pipe($.sourcemaps.init())
//etc...
}));
}
I'm working on a Typescript project that is transpiled to ES5 JS and then run through browserify to create a single .js bundle and sourcemap. The bundled sourcemaps point to the transpiled JS rather than the source TS even though I am generating sourcemaps which properly point to the source TS when transpiling to JS.
It's as if browserify is ignoring the existing sourcemaps pointing to the TS code and creating its own new maps to the transpiled JS code.
Here are my gulp tasks for reference- code is compiled to a temp folder and then browserified from there. This uses browserify-incremental to support incremental compilation.
Thanks!
Note: Via other SO questions I have already tried using tsify, per my understanding it won't work with my project as we use import syntax & commonjs, it reports compile issues where tsc and gulp-typescript do not (same errors whether used via gulp or via CLI). I also tried minifyify but it did not solve the issue.
var gulp = require('gulp'),
ts = require('gulp-typescript'),
browserify = require('browserify'),
browserifyInc = require('browserify-incremental'),
source = require('vinyl-source-stream'),
del = require('del'),
sourcemaps = require('gulp-sourcemaps'),
buffer = require('vinyl-buffer'),
xtend = require('xtend');
var tsProject = ts.createProject('tsconfig.json');
//COMPILE TS
gulp.task('compileTs', function () {
var sourceTsFiles = [config.src.tsFiles, config.src.tsTypes];
var tsResult = gulp.src(sourceTsFiles)
.pipe(sourcemaps.init())
.pipe(ts(tsProject));
return tsResult.js
.pipe(sourcemaps.write('.', {
//includeContent: false,
//sourceRoot: "../../src/js/"
}))
.pipe(gulp.dest(config.tempDir));
});
//BUNDLE BUILT TS->JS
gulp.task('bundleJs', [], function () {
var b = browserify(xtend(browserifyInc.args, {
entries: config.tempDir + '/main.js',
extensions: ['.js', '.jsx'],
debug: true
}));
browserifyInc(b, {cacheFile: config.tempDir + '/browserify-cache.json'});
return b.bundle()
.pipe(source('main.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.dest.jsDir));
});
Short answer
In the compileTs task you need to write the sourcemaps to the output .js files, instead of dedicated .map files. You also need to set includeContent to true, and specify the correct sourceRoot.
Then in the bundleJs task, having browserify debug true is enough to generate sourcemaps.
More details
Some package doesn't provide the necessary source data to the sourcemaps utility in the bundle task. Luckily sourcemaps can re-read the .ts file. For that recovery step to work, it needs correct file paths, so that's why the correct sourceRoot in the TypeScript compilation task is so crucial.
There seem to be other gotchas here as well. For example if you write the sourcemaps to a dedicated .map file in the TypeScript compilation task, then later the bundle task will generate sourcemaps that point to the compiled .js files. So it's again crucial that the compilation task embeds the sourcemaps into the actual .js files.
If the debug flag for browserify is true, it will generate sourcemaps. The extra gulp-sourcemaps layering here has a buggy interaction and should be removed.
A working example from real life
Directory structure
proj
/ts
/def
my-declarations.d.ts
/src
my-sources.ts
/tmp
temp-files-get-created-here-by-gulp.js
tsconfig.json
/web
/static
/js
final-result-goes-here.js
gulpfile.js
package.json
tsconfig.json
{
"compilerOptions": {
"noImplicitAny": true,
"removeComments": true,
"declaration": false,
"jsx": "React",
"target": "ES5",
"module": "CommonJS"
},
"exclude": [
"tmp"
]
}
package.json
{
"name": "my-awesome-project",
"version": "0.1.0",
"devDependencies": {
"browserify": "^13.0.1",
"gulp": "^3.9.1",
"gulp-sourcemaps": "^1.6.0",
"gulp-typescript": "^2.13.6",
"gulp-uglify": "^1.5.3",
"gulp-util": "^3.0.7",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
}
}
gulpfile.js
var path = require('path');
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var ts = require('gulp-typescript');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var debug = false;
var paths = {
tsConfig: 'ts/tsconfig.json',
scriptsSrc: ['ts/def/**/*.ts', 'ts/src/**/*.ts', 'ts/src/**/*.tsx'],
scriptsDst: 'web/static/js',
outDev: 'bundle.dev.js',
outFinal: 'bundle.js',
tempDst: 'ts/tmp',
entry: 'ts/tmp/entry.js'
};
var tsProject = ts.createProject(paths.tsConfig, { noExternalResolve: true });
gulp.task('ts', function () {
var tsResult = tsProject.src().pipe(sourcemaps.init()).pipe(ts(tsProject));
return tsResult.js.pipe(sourcemaps.write('', { debug: debug, includeContent: true, sourceRoot: './ts/src' })).pipe(gulp.dest(paths.tempDst));
});
gulp.task('dev', ['ts'], function() {
var bsfy = browserify({ entries: paths.entry, debug: true }); // Debug true generates sourcemaps
return bsfy.bundle()
.on('error', gutil.log)
.pipe(source(path.join(paths.scriptsDst, paths.outDev)))
.pipe(buffer())
.pipe(gulp.dest('./'));
});
gulp.task('final', ['ts'], function() {
process.env.NODE_ENV = 'production';
var bsfy = browserify({ entries: paths.entry, debug: false });
return bsfy.bundle()
.on('error', gutil.log)
.pipe(source(path.join(paths.scriptsDst, paths.outFinal)))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./'));
});
// Rerun the dev task when a file changes
gulp.task('watch', function() {
gulp.watch(paths.scriptsSrc, ['dev']);
});
// By default run all the tasks
gulp.task('default', ['dev', 'final']);
If you use both tasks at the same time, the second task will write new source maps. I'd suggest, that you only write source maps once, in the compileTs task.
I think this is the only problem in your tasks.
So I have the following gulp task:
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var babelify = require("babelify");
gulp.task('make:flare-currency', function() {
return browserify({entries: [
'src/add-new-currency/flare-currency.js',
'src/add-new-currency/currencies/set_up_currencies.js'
]})
.transform(babelify)
.bundle()
.pipe(source('Flare-Currency.js'))
.pipe(gulp.dest('dist/flare/currency/'));
});
I have the following package.json:
{
"name": "flare-collection",
"description": "collection of scripts for the RPG Maker MV system.",
"version": "0.0.1",
"dependencies": {
"gulp": "3.9.0",
"browserify": "11.2.0",
"vinyl-source-stream": "1.1.0",
"babelify": "6.4.0",
"underscore.string": "2.3.0"
}
}
When I try to do, inside: src/add_new_currencies/flare_currency.js
var UnderScoreString = require('underscore.string/string');
I get:
Error: Cannot find module 'underscore.string/string' from
'/Users/AdamBalan/Documents/Flare-Collection/src/add_new_currencies'
All of my require statements require that I do: var bla = require('some/file/to/include.js')
All of my classes (I am using es6) have, at the bottom of the file: module.exports = ClassName;
Why am I getting this error?
More importantly, why do I have to include the path to the js file?
underscore.string don't have a string submodule (function). If You want load all packages try _s = require('underscore.string'). If You want load single module like slugify try slugify = require('underscore.string/slugify').
You don't need to include the path to the js file. If you select the directory, then node.js try to find index.js file.
I had a similar question here that has merged into a bit more research on my part and a new way this could work.
Basically I'm trying to have all of my .js and .coffee files within one gulp.src() object and based on the extension, do relevant tasks.
What started off with gulp-if has turned into me using gulp-filter which I prefer honestly. The catch I'm running into right now is getting this all to work with gulp-sourcemaps. The current task seems to override the other -- but I'd ultimately like everything to be concatenated in one file, source-mapped in another and have each file extension run its respective tasks. You'll see the uglify task is commented out; as that's what keeps yelling at me; without a whole bunch to go off of. When I do get the filters to work and I have a CoffeeScript error, I noticed that coffeescriptlint() will do its job, but then my watch command; while still running, doesn't respond to anything.
It seems like I might be going down the path of extracting each sourcemap using something like gulp-extract-sourcemap, but am not sure if that's the right way to go.
Normally I'd separate out the JS and Coffeescript task, but I have so many things co-mingling between the two that bringing them together with a simple filter seemed logical -- especially as I'm trying to figure out the sourcemaps for both.
I feel like this one is pretty close, so any nudges in the right direction would be greatly appreciated. Included current gulpfile.js and package.json if you want to spin it up. Thanks!
Gulpfile.js
// Load plugins
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
coffee = require('gulp-coffee'),
changed = require('gulp-changed'),
coffeelint = require('gulp-coffeelint'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
notify = require('gulp-notify'),
concat = require('gulp-concat'),
filesize = require('gulp-size'),
livereload = require('gulp-livereload'),
duration = require('gulp-duration'),
gutil = require('gulp-util'),
gFilter = require('gulp-filter');
gulp.task('scripts', function() {
var jsBuildDir = 'assets/js/build/',
jsFilter = gFilter('**/*.js'),
coffeeFilter = gFilter('**/*.coffee');
return gulp.src([
'assets/js/src/_init.coffee',
'assets/js/src/_init.js'
])
.pipe(coffeeFilter)
.pipe(coffeelint().on('error', gutil.log))
.pipe(coffeelint.reporter())
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}).on('error', gutil.log))
.pipe(sourcemaps.write('../../maps'))
.pipe(coffeeFilter.restore())
.pipe(jsFilter)
.pipe(jshint({
'boss': true,
'sub': true,
'evil': true,
'browser': true,
'globals': {
'module': false,
'require': true
}
}),
jshint.reporter('jshint-stylish'))
.pipe(jsFilter.restore())
.pipe(concat('scripts.min.js'))
//.pipe(uglify())
.pipe(filesize({
title: 'Scripts:'
}))
.pipe(gulp.dest(jsBuildDir))
.pipe(duration('building script files'))
.pipe(notify({ message: 'Coffeescript task complete' }));
});
// Default task
gulp.task('default', ['scripts']);
// Watch
gulp.task('watch', function() {
gulp.watch(['assets/js/src/**/*.js', 'assets/js/src/**/*.coffee'], ['scripts']);
// Create LiveReload server
var server = livereload();
// Watch files in patterns below, reload on change
gulp.watch(['assets/js/build/*']).on('change', function(file) {
server.changed(file.path);
});
});
Package.json
{
"devDependencies": {
"gulp": "^3.8.8",
"gulp-changed": "^1.0.0",
"gulp-coffee": "^2.2.0",
"gulp-coffeelint": "^0.4.0",
"gulp-concat": "^2.4.0",
"gulp-duration": "0.0.0",
"gulp-filter": "^1.0.2",
"gulp-jshint": "^1.8.4",
"gulp-livereload": "^2.1.1",
"gulp-notify": "^1.6.0",
"gulp-size": "^1.1.0",
"gulp-sourcemaps": "^1.2.2",
"gulp-uglify": "^1.0.1",
"gulp-util": "^3.0.1",
"jshint-stylish": "^0.4.0"
}
}
I guess you wrapped the sourcemaps.init() and sourcemaps.write() around the wrong section of your pipe. I put the commands where I assume they belong. See below.
I used gulp-filter quite a few times as well. However, I kept it to a minimum to not overcomplicate things. I found run-sequence very helpful. (Also check out some of my gulpfiles here and here.)
Your scenario I would approach like this:
var runSequence = require('run-sequence');
// ...
gulp.task('scripts', function (done) {
runSequence('lint', 'build', done);
});
gulp.task('lint', function (done) {
runSequence('lint-coffee', 'lint-js', done);
});
gulp.task('lint-coffee', function () {
// Just lint your coffee files here...
});
gulp.task('lint-js', function () {
// Just lint your js files here...
});
gulp.task('build', function () {
return gulp.src([
'assets/js/src/_init.coffee',
'assets/js/src/_init.js'
])
.pipe(coffeeFilter)
.pipe(coffee({bare: true}).on('error', gutil.log))
.pipe(coffeeFilter.restore())
.pipe(sourcemaps.init())
.pipe(concat('scripts.min.js'))
.pipe(uglify())
.pipe(sourcemaps.write('../../maps'))
.pipe(gulp.dest(jsBuildDir));
});