Babel Not working for imports from node_modules - babeljs

I just discovered RollUP and I am stuck with an issue where Babel does not run for imports from node_modules.
Here is an example:
My Javascript Code
import { _map } from "#varunsridharan/js-vars"
const myarray = _map.call([1,2,3,4],(x)=> x * 2);
console.log(myarray);
Rollup Config
import { babel } from '#rollup/plugin-babel';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import { uglify } from 'rollup-plugin-uglify';
import filesize from 'rollup-plugin-filesize';
import visualizer from 'rollup-plugin-visualizer';
export default {
input: './src/index.js',
output: {
file: './dist/myfile.min.js',
format: 'iife',
plugins: [
uglify( { mangle: true } ),
]
},
plugins: [
nodeResolve(),
babel(),
filesize(),
visualizer()
]
};
When I run rollup -c in CLI I get this output:
babelHelpers: 'bundled' option was used by default. It is recommended to configure this option explicitly, read more here: https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers
198 | * Array Related Vars.
199 | */
> 200 | const Arr = Array;
| ^ Unexpected token: keyword «const»
201 | const _Arrayprop = Arr.prototype;
202 | const _filter = _Arrayprop.filter;
203 | const _push = _Arrayprop.push;
[!] (plugin uglify) Error: Unexpected token: keyword «const»
SyntaxError: Unexpected token: keyword «const»
at JS_Parse_Error.get (eval at <anonymous> (E:\localhost\www\javascript\dizzle\node_modules\uglify-js\tools\node.js:18:1), <anonymous>:69:23)
at reportError (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:107:11)
at reportClientError (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:87:10)
at execFunction (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:157:5)
at execHelper (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:139:5)
at execMethod (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:143:5)
at process.<anonymous> (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:64:7)
at process.emit (events.js:315:20)
at emit (internal/child_process.js:876:12)
at processTicksAndRejections (internal/process/task_queues.js:85:21)
Based on the output i was able to understand that babel did not run for the imported modules. so i checking the options provided for rollup babel plugin # (https://github.com/rollup/plugins/tree/master/packages/babel) and found that it has include AND exclude options and i tried with the below config
babel( {
include: [ "node_modules/#varunsridharan/*/**", "./src/**" ],
exclude: "node_modules/**",
} ),
Still, nothing happened so I tried without ./src/** in babel include config and found that babel is not running in my main javascript file which imports the node_modules's file
Node Module Project Link: https://github.com/varunsridharan/js-vars

Related

Flow Enums correctly parsed but not transformed

In my React app, I'm trying to migrate from my "old school" JS enums to Flow Enums:
https://flow.org/en/docs/enums/
(I think) I've done everything listed here:
https://flow.org/en/docs/enums/enabling-enums/
eslint and flow check are both happy (zero error) and the enums work as expected when I type code.
But when I start my app, they are not transformed and I get this:
ERROR in ./src/types.js
Module build failed (from ../../node_modules/babel-loader/lib/index.js):
SyntaxError: C:\foo\src\types.js: Unexpected token, expected "{" (16:7)
14 | |};
15 |
> 16 | export enum FooEnum {
| ^
17 | On,
18 | Off,
19 | Default
at instantiate (C:\foo\node_modules\#babel\parser\lib\index.js:72:32)
at constructor (C:\foo\node_modules\#babel\parser\lib\index.js:366:12)
at FlowParserMixin.raise (C:\foo\node_modules\#babel\parser\lib\index.js:3453:19)
at FlowParserMixin.unexpected (C:\foo\node_modules\#babel\parser\lib\index.js:3491:16)
at FlowParserMixin.parseExport (C:\foo\node_modules\#babel\parser\lib\index.js:16044:16)
at FlowParserMixin.parseExport (C:\foo\node_modules\#babel\parser\lib\index.js:6170:24)
at FlowParserMixin.parseStatementContent (C:\foo\node_modules\#babel\parser\lib\index.js:14893:27)
at FlowParserMixin.parseStatement (C:\foo\node_modules\#babel\parser\lib\index.js:14777:17)
at FlowParserMixin.parseStatement (C:\foo\node_modules\#babel\parser\lib\index.js:5951:24)
at FlowParserMixin.parseBlockOrModuleBlockBody (C:\foo\node_modules\#babel\parser\lib\index.js:15420:25)
Package-wise, all of them are in their latest version and I've installed:
babel-plugin-transform-flow-enums
eslint-plugin-ft-flow
flow-enums-runtime
My Babel config is:
"babel": {
"plugins": [
"#babel/plugin-proposal-class-properties",
[
"#babel/plugin-syntax-flow",
{
"enums": true
}
],
"babel-plugin-transform-flow-enums"
],
"presets": [
"#babel/preset-env",
"#babel/preset-flow",
"#babel/preset-react"
]
},
Also, calling Babel from a command line correctly transforms the enum. I'm using this command:
npx babel src/types.js
What could I have missed?
So, after struggling for hours, I eventually found out that
react-app-rewired was messing up with my Babel plugins.
I ended up installing customize-cra, which allowed me to explicitely use my Babel config:
const {useBabelRc, override} = require('customize-cra');
module.exports = override(
useBabelRc()
);

reexport - SyntaxError: Unexpected token 'export'

There is such a file. That imports from API and exports at once.
export { extractValue, parse, parseCommand } from './parser'
export { Manager, EVENTS } from './manager'
export { runCLI, runCommand, bootstrapCommandManager } from './cli'
I receive an error:
export { extractValue, parse, parseCommand } from './parser'
^^^^^^
SyntaxError: Unexpected token 'export'
There is my babel.config.js
module.exports = {
presets: [['#babel/preset-env', {targets: {node: 'current'}}]],
plugins: [
['#babel/plugin-transform-modules-commonjs'],
['#babel/plugin-proposal-decorators', {'legacy': true}],
['#babel/plugin-proposal-class-properties'],
['#babel/plugin-proposal-export-default-from']
]
};
#babel/plugin-proposal-export-default-from does not help.
It did not compile files from node_modules directory. An ignore rule had to be set.
It works
Variant A babel-node
npx babel-node --ignore="/node_modules\/(?\!console-command-manager)/" --config-file ./babel.config.js ./src/index.js
I fault to move --ignore argument into ./babel.config.js
Variant B
Node executtion with -r runner.js
Execution
node -r ./runner.js src/index.js
Runner
const config = require('./babel.config.js')
console.log(config)
require("#babel/register")({
extensions: ['.js'],
ignore: [
/node_modules[\\/](?!console-command-manager)/
],
...config
});

Jest: Cannot use import statement outside a module

I got an error when I run test using Jest, I tried to fix this error for 2 hours. But, I couldn't fix it. My module is using gapi-script package and error is occurred in this package. However, I don't know why this is occurred and how to fix it.
jest.config.js
module.exports = {
"collectCoverage": true,
"rootDir": "./",
"testRegex": "__tests__/.+\\.test\\.js",
"transform": {
'^.+\\.js?$': "babel-jest"
},
"moduleFileExtensions": ["js"],
"moduleDirectories": [
"node_modules",
"lib"
]
}
babel.config.js
module.exports = {
presets: [
'#babel/preset-env',
]
};
methods.test.js
import methods, { typeToActions } from '../lib/methods';
methods.js
import { gapi } from "gapi-script";
...
Error Message
C:\haram\github\react-youtube-data-api\node_modules\gapi-script\index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ gapi, gapiComplete } from './gapiScript';
SyntaxError: Cannot use import statement outside a module
What is wrong with my setting?
As of this writing, Jest is in the process of providing support for ES6 modules. You can track the progress here:
https://jestjs.io/docs/en/ecmascript-modules
For now, you can eliminate this error by running this command:
node --experimental-vm-modules node_modules/.bin/jest
instead of simply:
jest
Be sure to check the link before using this solution.
I solved this with the help of Paulo Coghi's answer to another question -
Does Jest support ES6 import/export?
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
Jest needs babel to work with modules.
For the testing alone, you do not need jest.config.js, just name the testfiles xxx.spec.js or xxx.test.js or put the files in a folder named test.
I use this babel.config.js:
module.exports = function (api) {
api.cache(true)
const presets = [
"#babel/preset-env"
]
return {
presets
}
}
Adding "type": "module" in package.json or using mjs as stated in other answers is not necessary when your setup is not too complicated.
I have also faced the same issue and this was resolved by adding following command-line option as a environment variable.
export NODE_OPTIONS=--experimental-vm-modules npx jest //linux
setx NODE_OPTIONS "--experimental-vm-modules npx jest" //windows
Upgrading Jest (package.json) to version 29 (latest as of now) solved this problem for me.

babel-preset-es2015 Failed to compile destructuring assignment syntax

I'm using babel to compile some es6 code, when I trying destructuring assignment it work well for array , but not Object destructuring. the problem code are as follow.
test(){
var {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
console.log(a);
console.log(rest);
}
the error log:
ERROR in ./src/js/index.js
Module build failed: SyntaxError: Unexpected token (11:13)
9 | test(){
10 |
> 11 | var {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
| ^
12 |
13 | console.log(a);
14 | console.log(rest);
# multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/js/index.js
webpack: Failed to compile.
my webpack.config.js
var webpack = require("webpack");
var path = require("path");
module.exports = {
entry: "./src/js/index.js",
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist',
filename: "bundle.js"
},
module:{
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query:{
presets:['react', 'es2015']
},
},
{
test: /\.css$/,
loader: 'style-loader!css-loader',
}
]
},
}
anyone had solved the same problem? hope for you help thanks a lot.
Install babel-preset-env by running following command on terminal
npm install babel-preset-env --save-dev
Then create .babelrc file in your project and write following JSON
{
"presets": ["env"]
}
for more information follow following link
babel-preset-env
es2015 does not include spread properties, you can add a plugin to transform them
Take a look at this link and add this preset to your presets property

Babel 7 and babel-polyfill

After updating to babel 7 beta, looks like babel polyfill does not transpile before bundle. I updated all scoped packages like this one "#babel/polyfill": "7.0.0-beta.36". And changed imports for two files from import 'babel-polyfill' to import '#babel/polyfill'. How to use babel/pollyfill with babel env and babel 7. Should I use babel/polyfill when use useBuiltIns: 'usage', with targets?
.babelrc.js
const nodeEnv = process.env.NODE_ENV || 'development'
let presetEnvConfig, plugins
if (nodeEnv === 'test'){
presetEnvConfig = {targets: {node: 'current'}}
plugins = ['istanbul']
} else {
presetEnvConfig = {
targets: {
browsers: ['last 2 versions', 'ie >= 11']
},
modules: false
}
plugins = ['react-hot-loader/babel']
}
const config = {
presets: [
['#babel/preset-env', presetEnvConfig],
'#babel/react',
'#babel/stage-2'
],
plugins,
}
types.js
import keyMirror from '../../../utils/keyMirror'
export default keyMirror({
Unassign: null,
Reassign: null,
QuickAssignment: null,
}, 'TagAssignmentTypes')
index.js
<Assignment
assignee={assignee}
tagId={tagId && tagId.toString(16)}
assignmentType={assignmentTypes.Reassign}
onRequestClose={() => this.setState({isAssignmentInProgress: false})}
onChange={onChange}
/>
#babel/polyfill is a wrapper package which only includes imports of stable core-js features (in Babel 6 it also included proposals) and regenerator-runtime/runtime, needed by transpiled generators and async functions. This package doesn't make it possible to provide a smooth migration path from core-js#2 to core-js#3: for this reason, it was decided to deprecate #babel/polyfill in favor of separate inclusion of required parts of core-js and regenerator-runtime.
Instead of
import "#babel/polyfill";
you should use those 2 lines:
import "core-js/stable";
import "regenerator-runtime/runtime";
Don't forget install those dependencies directly!
npm i --save core-js regenerator-runtime
Change
#babel/stage-2 to #babel/preset-stage-2
The following worked for me, add
**.babelrc**
{
"presets": [
["#babel/env"]
]
}
**app.js**
import "core-js/stable";
import "regenerator-runtime/runtime";
*Install as pointed by gianmarco*
npm i --save core-js regenerator-runtime