Require not working the way I thought it would - javascript

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.

Related

Gulp and browserify give error: Cannot find module 'jquery' from 'C:....'

The error I receive is:
Error: Cannot find module 'jquery' from 'F:...\newstyle\assets\lib\helper\html\img\js'
at
C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:46:17
at process (C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:173:43)
at ondir (C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:188:17)
at load (C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:69:43)
at onex (C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:92:31)
at C:\Users...\AppData\Roaming\npm\node_modules\browserify\node_modules\browser-resolve\node_modules\resolve\lib\async.js:22:47
at FSReqWrap.oncomplete (fs.js:153:21)
My directory structure is as follows:
newstyle/assets/npm/index.js
newstyle/assets/npm/package.json
newstyle/assets/npm/gulpfile.js
newstyle/assets/lib/helper/html/img/js/img.module.js
My package.json looks like this:
{
"name": "newstyle",
"version": "1.0.0",
"description": "styles and libraries",
"main": "index.js",
"dependencies": {
"#tschallacka/assetmanager": "^1.0.0",
"#tschallacka/jquery.oc.foundation": "^1.0.2",
"#tschallacka/jquery.render": "^1.0.0",
"#tschallacka/jquery.request": "^1.0.0",
"#tschallacka/oc.foundation.base": "^1.0.1",
"#tschallacka/oc.foundation.controlutils": "^1.0.1",
"#tschallacka/oc.foundation.request": "^1.0.0",
"animate.css": "^3.7.0",
"bootstrap-less": "^3.3.8",
"flexslider": "^2.7.2",
"font-awesome": "^4.7.0",
"jquery": "^3.4.1",
"jquery-touchswipe": "^1.6.19",
"jquery.easing": "^1.4.1",
"lazysizes": "^4.1.8",
"liquidslider": "git+https://git#github.com/KevinBatdorf/liquidslider.git",
"popper.js": "^1.15.0",
"sweetalert2": "^8.11.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
My index.js like this:
require('#tschallacka/oc.foundation.base');
require('#tschallacka/oc.foundation.controlutils');
// ====================== TROUBLE CAUSING LINE!! ==========================
require('../assets/lib/helper/html/img/js/img.module.js');
the code in newstyle/assets/lib/helper/html/img/js/img.module.js
var $ = require('jquery');
var Base = require('#tschallacka/oc.foundation.base');
var controlUtils = require('#tschallacka/oc.foundation.controlutils');
My gulpfile.js
'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var log = require('gulplog');
var less = require('gulp-less');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
gulp.task('javascript', function () {
// set up the browserify instance on a task basis
var b = browserify({
entries: './index.js', // Source name
debug: true
});
return b.bundle()
.pipe(source('closure.js'))// Resulting filename
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
// Add transformation tasks to the pipeline here.
.pipe(uglify())
.on('error', log.error)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('../js/'));
});
gulp.task('watch', function () {
gulp.watch('./*.less', ['less']);
});
gulp.task('less', function () {
return gulp.src('./style.less')
.pipe(less({
relativeUrls: true
}).on('error', function (err) {
console.log(err);
}))
.pipe(cssmin().on('error', function(err) {
console.log(err);
}))
.pipe(rename('closure.css'))
.pipe(gulp.dest('../css/'));
});
When I run this without the trouble causing line, everything works fine, it finds the modules and it compiles without a hitch. No problems with not finding the modules.
But when I require that script, the module I required as test from the "parent" script suddenly cannot be found anymore, even though it should still be in the cache by string name.
It does work if I 'require' the files by filename, but that's less than desirable because then I constantly need to check directory nesting.
What causes this and how can I resolve this?
Things I've tried:
setting basedir
var b = browserify({
entries: './index.js', // Source name
debug: true,
basedir: __dirname
});
npm update from 6.4.1 to 6.9.0
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade
updated gulp:
+ gulp#4.0.2
updated 6 packages in 19.938s
The solution is rather simple, but not easy to get to the conclusion what causes the error, you have to add node_modules to the 'paths' variable of browserify in your gulpfile.js
// set up the browserify instance on a task basis
var b = browserify({
entries: './index.js', // Source name
debug: true,
paths: ['./node_modules'] // <--- this line here
});

babel.transform() function not using .babelrc or package.json config

I am trying to use Babel to transform ES6 to ES5 that is already loaded into a variable. However, I am finding contrary to the Babel documentation babel.transform() is not using the configuration files to transform the code.
The following demonstrates my issue:
package.json:
{
"name": "babel-test",
"version": "1.0.0",
"main": "index.js",
"babel": {
"presets": [
["env", {
"targets": {
"ie": 8
}
}]
]
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-preset-env": "^1.6.1"
}
}
test.js:
const a = 0
index.js:
const babel = require('babel-core')
console.log(babel.transform('const a = 0').code)
console.log(babel.transformFileSync('test.js').code)
CLI:
$ node index.js
const a = 0;
"use strict";
var a = 0;
As you can see babel.transformFileSync() is using the config and babel.transform() isn't.
How do I get babel.transform() to use the config file?
.babelrc files are searched for relative to the file being compiled, so if it doesn't know the name of the file, it can't find it.
babel.transform('const a = 0', {filename: "test.js"}).code)
for instance will work.

Gulp Typescript + Browserify; Bundled sourcemap points to transpiled JS rather than source TS

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.

Javascript 6to5 (now Babel) export module usage

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

Loading javascript plugs in order with gulp / browserify

Soooooo.... I'm have a helluva time trying to figure out browserify.
Here's my app.js file:
var $ = require('../lib/jquery');
var foundation = require('../lib/foundation/foundation');
$(document).ready(function($){
$(document).foundation();
});
when i try loading the browserified file, I get this error:
Uncaught ReferenceError: jQuery is not defined
I'm using the latest version of jquery. Any idea what's going on?
so uh, i solved the problem by using browserify-shim
here's what i added to my package.json file:
"browser": {
"jquery": "./js/lib/jquery.js"
},
"browserify-shim": {
"jquery": "$"
},
"browserify": {
"transform": [ "browserify-shim" ]
},
"dependencies": {
"browserify-shim": "~3.2.0"
}
ta da

Categories

Resources