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.
Related
I use the babel.js node.js API to compile react jsx and js scripts.
I have the following node.js script for example:
// react_transform.js
const fs = require("fs");
code = fs.readFileSync("./samples/sample4.js", 'utf8');
result2 = require("#babel/core").transformSync(code, {
presets: [
"#babel/preset-env",
"#babel/preset-react",
],
plugins: [
"#babel/plugin-transform-runtime",
],
});
fs.writeFileSync(`./out/out4.js`, result2.code);
console.log("y.");
And the input file that has the jsx code is like:
// sample4.js
ReactDOM.render(
<div>
<p>
hoge.
</p>
</div>
,
document.getElementById('root')
);
$(".__upvote").click(async function (e) {
alertify.warning("You need to login.");
});
Without the "#babel/plugin-transform-runtime", line in the node.js script, when I use the script on the browser (where the output code should be located in the production), it causes an error:
VM496:9 Uncaught ReferenceError: regeneratorRuntime is not defined
So, I did research and added the line. But now I started to get a new error:
VM830:5 Uncaught TypeError: _interopRequireDefault is not a function
By the way the output js file is as follows:
// out4.js
"use strict";
var _interopRequireDefault = require("#babel/runtime/helpers/interopRequireDefault");
var _regenerator = _interopRequireDefault(require("#babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("#babel/runtime/helpers/asyncToGenerator"));
ReactDOM.render( /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("p", null, "hoge.")), document.getElementById('root'));
$(".__upvote").click( /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(e) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
alertify.warning("You need to login.");
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}());
So I again did research about the new error, found an SO post:
reactjs - How to fix TypeError _interopRequireDefault is not a function in Create React App - Stack Overflow
People say:
Add #babel/runtime to the dependency section. That will fix it.
After add "#babel/runtime", I fixed it
So I added that "#babel/runtime" to package.json then npm install-ed. Now the package.json is like (I ommited irrelevant lines):
{
"name": "tmp",
"version": "1.0.0",
"description": "",
"main": "lodash_dev.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/runtime": "^7.17.8",
},
"devDependencies": {
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#babel/plugin-transform-react-jsx": "^7.17.3",
"#babel/plugin-transform-runtime": "^7.17.0",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
}
}
Then re-run the node.js script, I get the output, I tested it on the page on the browser, however, for some reason the error still persists.
How can I fix this? Thanks.
You're transforming your code with Babel, but you're not running a bundler such as esbuild or webpack.
require() is not a thing in the browser. The bundler's responsibility (among other things) is to take all of those require() calls and resolve them into real modules, and end up with one (or more) .js files that contains all of the require()d code and no require()s.
It should be very simple this one, but I can't run it. I have installed the plugin according the their docs and written a simple example also according to their docs:
test.js:
import pluginTester from 'babel-plugin-tester'
pluginTester({
plugin: identifierReversePlugin,
snapshot: true,
tests: [
{code: '"hello";', snapshot: false},
{
code: 'var hello = "hi";',
output: 'var olleh = "hi";',
},
`
function sayHi(person) {
return 'Hello ' + person + '!'
}
console.log(sayHi('Jenny'))
`,
],
})
// normally you would import this from your plugin module
function identifierReversePlugin() {
return {
name: 'identifier reverse',
visitor: {
Identifier(idPath) {
idPath.node.name = idPath.node.name.split('').reverse().join('')
},
},
}
}
I have installed jest according to jest docs:
npm install jest --save-dev
My package.json file:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"#babel/cli": "^7.10.1",
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"babel-jest": "^26.0.1",
"babel-plugin-tester": "^9.2.0",
"jest": "^26.0.1"
}
}
I also have babel config as:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
I try to run npx jest test.js but it just spits out
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
I can run jest on a simple example without babel-plugin-tester, so everything seems to work, but I probably don't understand how it is intended to be used with jest. I feel so stupid.
This is stupid! I had to rename my testfile to fit *.test.js. Why don't jest trust me that the file I intend to run indeed contains tests?! This is obviously a stupid implementation of jest!!
Hours of wasted time.. thanks to stupid jest
I want simply import a function from an another file and I'm getting this error message:
SyntaxError: Cannot use import statement outside a module
I'm not using any html file. I'm using only js files with webpack that returns the result on the console with yarn start
Here is the code of the file that contains the function I want to export:
export function assert(value, desc) {
return value ? console.log(desc) : console.log('fail')
}
Here is the code of the file that I want to import the function:
import {assert} from './assert.js'
function juggle() {
var result = 0;
for(var n=0; n < arguments.length; n++) {
result += arguments[n]
}
this.result = result
}
var ninja1 = {}
var ninja2 = {}
juggle.apply(ninja1, [1,2,3,4])
juggle.call(ninja2, 5,6,7,8)
assert(ninja1.result === 10, "juggled via apply")
assert(ninja2.result === 26, "juggled via call")
Here is my package.json:
I don't know if it is userful to solve this issue, but here is, if you want to see it.
{
"name": "c",
"version": "1.0.0",
"main": "",
"scripts": {
"start": "node Cap_03/01_apply_e_call.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"webpack-dev-server": "^3.9.0"
},
"type": "module",
"devDependencies": {
"webpack": "^4.41.2"
},
"description": ""
}
As of Node 13.2.0+
Verify that you have the latest version of Node installed. Simply do one of the following:
Add "type": "module" to the nearest parent package.json. With this, all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.
OR
Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.
If you use an older Node version or have to
import statements are permitted only in ES modules.
For similar functionality in CommonJS, see import().
To make Node treat your file as a ES module you need to
add "type": "module" to package.json
add "--experimental-modules" flag to the node call
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.
There are many similar questions including answers here on stack overflow, but none of them have worked for me, so here I am asking you guys. I appreciate everyone's time.
I recently started using gulp with browserify, and that works great.
I then tried to use browserify for the front-end using: Backbone and Bootstrap3.
things are appearing to work, until I try to require the js file that comes with Bootstrap. I get an error in my chrome tools stating: jQuery is undefined.
I have attempted to shim it in, but I am very confused by the shim. I am using jQuery 2.1.1, so I should not need to shim jQuery, but it exists in the shim now, as I was desperate and trying everything. Here is my package.json and my main.js file:
--------------package.json------------------
{
"name": "gulp-backbone",
"version": "0.0.0",
"description": "Gulp Backbone Bootstrap",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Rob Luton",
"license": "ISC",
"devDependencies": {
"jquery": "^2.1.1",
"backbone": "^1.1.2",
"browserify": "^4.2.1",
"gulp": "^3.8.6",
"vinyl-source-stream": "^0.1.1",
"gulp-sass": "^0.7.2",
"gulp-connect": "^2.0.6",
"bootstrap-sass": "^3.2.0",
"browserify-shim": "^3.6.0"
},
"browser": {
"bootstrap": "./node_modules/bootstrap-sass/assets/javascripts/bootstrap.js",
"jQuery": "./node_modules/jquery/dist/jquery.min.js"
},
"browserify": {
"transform": ["browserify-shim"]
},
"browserify-shim": {
"jquery": "global:jQuery",
"bootstrap": {
"depends": [
"jQuery"
]
}
}
}
------------------------- main.js ----------------------
var shim = require('browserify-shim');
$ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var bootstrap = require('bootstrap');
/* the following logs fine if I comment out the bootstrap require, otherwise I get 'jQuery undefined' */
console.log(Backbone);
$(function() {
alert('jquery works');
});
You shouldn't need to shim jquery that way if you've installed it with npm. The following works for a project I've been writing:
I've also learned that using npm for bootstrap is kind of a PITA. I've been using bower to install and maintain certain front-end components when they need to be shimmed like this.
package.json:
{
"name": "...",
"version": "0.0.1",
"description": "...",
"repository": {
"type": "git",
"url": "..."
},
"browser": {
"d3js": "./bower_components/d3/d3.min.js",
"select2": "./bower_components/select2/select2.min.js",
"nvd3js": "./bower_components/nvd3/nv.d3.min.js",
"bootstrap": "./node_modules/bootstrap/dist/js/bootstrap.js"
},
"browserify": {
"transform": [
"browserify-shim",
"hbsfy"
]
},
"browserify-shim": {
"d3js": {
"exports": "d3",
"depends": [
"jquery:$"
]
},
"bootstrap": {
"depends": [
"jquery:jQuery"
]
},
"select2": {
"exports": null,
"depends": [
"jquery:$"
]
},
"nvd3js": {
"exports": "nv",
"depends": [
"jquery:$",
"d3js:d3"
]
}
},
"devDependencies": {
"browserify-shim": "~3.4.1",
"browserify": "~3.36.0",
"coffeeify": "~0.6.0",
"connect": "~2.14.3",
"gulp-changed": "~0.3.0",
"gulp-imagemin": "~0.1.5",
"gulp-notify": "~1.2.4",
"gulp-open": "~0.2.8",
"gulp": "~3.6.0",
"hbsfy": "~1.3.2",
"vinyl-source-stream": "~0.1.1",
"gulp-less": "~1.2.3",
"bower": "~1.3.3",
"cssify": "~0.5.1",
"gulp-awspublish": "0.0.16",
"gulp-util": "~2.2.14",
"gulp-rename": "~1.2.0",
"gulp-s3": "git+ssh://git#github.com/nkostelnik/gulp-s3.git",
"gulp-clean": "~0.2.4",
"process": "~0.7.0"
},
"dependencies": {
"backbone": "~1.1.2",
"jquery": "~2.1.0",
"lodash": "~2.4.1",
"d3": "~3.4.8",
"rickshaw": "~1.4.6",
"datejs": "~1.0.0-beta",
"moment": "~2.7.0"
}
}
js:
$ = jQuery = require('jquery');
var _ = require('lodash');
var Rickshaw = require('rickshaw');
var d3 = require('d3js');
var nvd3 = require('nvd3js');
var moment = require('moment');
require('datejs');
require('select2');
var bootstrap = require('bootstrap');
console.log(bootstrap)
Also - one sometimes useful thing is to have browserify-shim output its diagnostics. This is what my browserify.js task looks like:
var browserify = require('browserify');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
var process = require('process');
process.env.BROWSERIFYSHIM_DIAGNOSTICS=1;
var hbsfy = require('hbsfy').configure({
extensions: ['html']
});
gulp.task('browserify', ['images', 'less'], function(){
return browserify({
transform: ['hbsfy', 'cssify'],
entries: ['./src/javascript/app.js'],
})
.bundle({debug: true})
.on('error', handleErrors)
.pipe(source('app.js'))
.pipe(gulp.dest('./build/'));
});
There is error as I am using browserify which require the variable '$' or 'jQuery' to be defined.
adding the window to make it global resolve the error. Not sure if this would be the correct way to do, if not, let me know.
window.$ = window.jQuery = require('jquery');
var bootstrapjs = require('bootstrap-sass');
I've been wondering about this for a while. This simple solution does the job for me:
import foo from 'foo';
import bar from './bar';
import { default as $ } from "jquery";
global.$ = $;
global.jQuery = $; // This one does the trick for bootstrap!
// Boostrap's jQuery dependency only works with require, not with ES6 import!
const btp = require('bootstrap');
So to make Bootstrap to work with Browserify you're going to need one of Browserify CSS transforms.
First the index.js (browserify entry)
// Bootstrap needs jQuery on the Window
window.jQuery = $ = require('jquery');
// include popper.js if you want Bootstrap tooltips
window.Popper = require('popper.js');
// include bootstrap js libs (not the CSS libs as yet)
require('bootstrap');
// then the CSS Lib
require('bootstrap/dist/css/bootstrap.css');
NPM Installs:
npm install bootstrap#4.0.0-alpha.6 jquery popper.js
To use tooltips globally:
Per the Bootstrap docs.
$('[data-toggle="popover"]').popover();
I have a Browserify-Budo repo here. If you want to see it working.