Why is "-" (dash) giving "Unexpected token error" on Babelify with Gulp? - javascript

I am setting up (or actually modifying existing) project with Browserify and Babelify. For some reason I can't configure my gulpfile properly. The project itself is a React project, if it matters.
I got rid of most of the problems, but now I am getting "Unexpected token" error on Browserify. It is caused by React components or html elements with attribute names which have a dash, ie. the following:
<button type="button" data-toggle="collapse">
My Browserify task:
gulp.task('browserify', function() {
browserify('./src/js/main.js')
.transform(babelify.configure({
presets: ["react", "es2015"]
}))
.bundle()
.on('error', function(err){
process.stdout.write('' + err + '\n');
notifier.notify({
title: 'Error',
message: err,
sound: true,
wait: true
}, function (err, response) {
});
})
.pipe(source('main.js'))
.pipe(gulp.dest('dist/js'))
.pipe(connect.reload());
});
Package.json:
{
"name": "srcd-mockup",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"dependencies": {
"babel-preset-es2015": "^6.0.12",
"bootstrap-sass": "^3.3.5",
"browserify": "^11.2.0",
"flux": "^2.1.1",
"font-awesome": "^4.4.0",
"gulp": "^3.9.0",
"gulp-concat": "^2.6.0",
"jquery": "^2.1.4",
"lodash": "^3.10.1",
"node-notifier": "^4.3.1",
"react": "^0.14.1",
"react-dom": "^0.14.1",
"react-redux": "^4.0.0",
"react-router-component": "^0.27.2",
"reactify": "^1.1.1",
"redux": "^3.0.4",
"redux-logger": "^2.0.4",
"updeep": "^0.10.1",
"vinyl-source-stream": "^1.1.0"
},
"devDependencies": {
"babel-preset-react": "^6.0.12",
"babelify": "^7.0.2",
"gulp-connect": "^2.2.0",
"gulp-notify": "^2.2.0",
"gulp-sass": "^2.0.4",
"gulp-uglify": "^1.4.1",
"redux-devtools": "^2.1.5"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
What I tried before:
The weird thing here is that previously I had similar project with similar dependencies and config, and it worked fine.
Then I tried to set up the new one, and first I got Unexpected token error on this line on my main.js (initial render of React):
ReactDOM.render(<App />, document.getElementById('main'));
The error was caused by "(". Then there was no presets on Babelify.
If I only have "react" on presets, I get "ParseError: 'import' and 'export' may appear only with 'sourceType: module'", because of, well importing.
Questions:
Is this related to Babelify or can it be caused by other module or dependency?
Is this related to Babel 6?
Why is dash causing the error?
How should I set this up?

There appears to be a bug as of Babel version 6.0.12 which is rendering data-* tags as object keys without quoting them, resulting in invalid JS syntax.
You can use a pre-v6 version of Babel, or else wait for someone to submit a fix.
UPDATE:
A fix for this just got checked into the repo, so this will be fixed in the next release.

Related

How to solve [ERROR] TypeError: dep.getModuleEvaluationSideEffectsState is not a function?

I have created a docusaurus project. It was working fine. I added material ui search bar in the landing page. I am using github actions to deploy the project(CI/CD). Now when i push the code, iam getting this error.
[ERROR] TypeError: dep.getModuleEvaluationSideEffectsState is not a function
at NormalModule.getSideEffectsConnectionState (/github/workspace/website/node_modules/webpack/lib/NormalModule.js:1126:23)
at /github/workspace/website/node_modules/webpack/lib/optimize/SideEffectsFlagPlugin.js:244:19
at Hook.eval [as call] (eval at create (/github/workspace/website/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:12:16)
at Hook.CALL_DELEGATE [as _call] (/github/workspace/website/node_modules/tapable/lib/Hook.js:14:14)
at Compilation.seal (/github/workspace/website/node_modules/webpack/lib/Compilation.js:2804:42)
at /github/workspace/website/node_modules/webpack/lib/Compiler.js:1187:20
at /github/workspace/website/node_modules/webpack/lib/Compilation.js:2757:4
at _next2 (eval at create (/github/workspace/website/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:35:1)
at eval (eval at create (/github/workspace/website/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:71:1)
at /github/workspace/website/node_modules/webpack/lib/FlagDependencyExportsPlugin.js:385:11
I am not sure how to solve this. I have also attached package.json file.
{
"scripts": {
"examples": "docusaurus-examples",
"start": "docusaurus start",
"build": "docusaurus build",
"serve": "docusaurus serve",
"publish-gh-pages": "docusaurus-publish",
"write-translations": "docusaurus-write-translations",
"version": "docusaurus-version",
"rename-version": "docusaurus-rename-version",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"docusaurus": "docusaurus"
},
"engines": {
"node": ">=16.14.0"
},
"dependencies": {
"#azure/msal-browser": "^2.28.0",
"#azure/msal-react": "^1.4.4",
"#docusaurus/core": "^2.0.0-rc.1",
"#docusaurus/plugin-client-redirects": "^2.1.0",
"#docusaurus/plugin-content-docs": "^2.0.0-rc.1",
"#docusaurus/preset-classic": "^2.0.0-rc.1",
"#emotion/react": "^11.10.4",
"#emotion/styled": "^11.10.4",
"#fortawesome/react-fontawesome": "^0.1.18",
"#material-ui/core": "^4.12.4",
"#mui/material": "^5.10.8",
"axios": "^0.27.2",
"bootstrap": "^5.1.3",
"chart.js": "^3.8.0",
"clsx": "^1.1.1",
"docker": "^1.0.0",
"docusaurus": "^1.14.7",
"docusaurus-lunr-search": "^2.1.15",
"docusaurus-pdf": "^1.2.0",
"docusaurus2-dotenv": "^1.4.0",
"env-cmd": "^10.1.0",
"jquery": "^3.6.0",
"moment": "^2.29.4",
"react": "^17.0.2",
"react-bootstrap": "^2.4.0",
"react-chartjs-2": "^4.3.1",
"react-dom": "^17.0.2",
"react-icons": "^4.4.0",
"react-markdown-editor-lite": "^1.3.2",
"react-paginate": "^8.1.3",
"react-player": "^2.10.1",
"react-scripts": "^5.0.1"
}
}
Can someone help me with this?
Are you using the plugin docusaurus2-dotenv?
We found the same problem here, and the root cause is this plugin. We remove this plugin from the package.json and from the docusaurus.config.js. We replaced it inside the docusaurus.config.js with the plugin docusaurus-plugin-dotenv, like this:
// Before
plugins:
[
// Other plugins
['docusaurus2-dotenv', { systemvars: true }],
]
// After
plugins:
[
// Other plugins
[
'docusaurus-plugin-dotenv',
{
path: "./.env",
systemvars: true,
}
]
]
This error occurs because the plugin 'docusaurus2-dotenv' is depreciated, although the docusaurus documentation itself recommends using it.
After removing it from our project, we noticed that even some vulnerabilities have gone away.
Here's the link of the new plugin: docusaurus-plugin-dotenv

A dynamic import() which is available in all CommonJS modules

I got the below error when I'm trying to run npm install. Error Message:
taskRepository: Failed to require task module for setTimestamp: require() of ES Module ......\node_modules\dateformat\lib\dateformat.js from .....\setTimestamp.js not
supported.
Instead change the require of dateformat.js in .....\setTimestamp.js to a dynamic import() which is available in all CommonJS modules.
In setTimestamp.js file, we have
const stringReplacer = require("#ui5/builder").processors.stringReplacer;
const df = require("dateformat");
This is a SAPUI5 based cloud application and we've 2 package.json files.
Under Root folder:
"version": "1.2.0",
"devDependencies": {
"#ui5/builder": "^2.11.5",
"#ui5/cli": "^2.14.10",
"#wdio/cli": "7.23.0",
"#wdio/cucumber-framework": "7.23.0",
"#wdio/junit-reporter": "7.23.0",
"#wdio/local-runner": "7.23.0",
"#wdio/selenium-standalone-service": "7.23.0",
"#wdio/spec-reporter": "7.23.0",
"chai": "^4.3.6",
"chromedriver": "^104.0.0",
"cucumber-html-reporter": "5.5.0",
"nyc": "^15.1.0",
"opa-e2e": "^1.0.11",
"request": "^2.88.2",
"request-promise": "^4.2.6",
"shelljs": "^0.8.5",
"type": "module",
"wdio-chromedriver-service": "^7.3.2",
"wdio-cucumber-reporter": "0.0.2",
"wdio-cucumberjs-json-reporter": "^4.4.3"
},
"resolutions": {
"terser": ">=5.14.2",
"markdown-it": ">=12.3.2",
"marked": ">=4.0.10",
"shelljs": ">=0.8.5",
"ejs": ">=3.1.7",
"node-fetch": ">=2.6.7",
"got": ">=11.8.5",
"follow-redirects": ">=1.14.8",
"minimist": ">=1.2.6"
}
Inner one:
"ui5": {
"dependencies": [
"ui5-middleware-livereload",
"ui5-middleware-simpleproxy",
"ui5-middleware-servestatic",
"#dwc/ui5-middleware-dwc"
]
},
"devDependencies": {
"#dwc/ui5-middleware-dwc": "^1.4.2-20220817085704",
"#ui5/cli": "^2.14.10",
"dateformat": "^5.0.3",
"env-cmd": "^10.1.0",
"eslint": "^8.22.0",
"karma": "6.4.0",
"karma-chrome-launcher": "^3.1.1",
"karma-coverage": "^2.2.0",
"karma-junit-reporter": "^2.0.1",
"karma-qunit": "^4.1.2",
"karma-sinon": "^1.0.5",
"karma-ui5": "2.4.0",
"nyc": "^15.1.0",
"qunitjs": "^2.4.1",
"rimraf": "^3.0.2",
"shelljs": "^0.8.5",
"start-server-and-test": "^1.14.0",
"ui5-middleware-livereload": "^0.7.0",
"ui5-middleware-servestatic": "^0.4.0",
"ui5-middleware-simpleproxy": "^0.9.1",
"wdio-chromedriver-service": "7.3.2"
},
"resolutions": {
"terser": ">=5.14.2",
"markdown-it": ">=12.3.2",
"marked": ">=4.0.10",
"ua-parser-js": ">=0.7.24",
"log4js": ">=6.4.0",
"karma": ">=6.3.16",
"follow-redirects": ">=1.14.8",
"minimist": ">=1.2.6"
}
I tried to fix this issue by using:
npm i node-fetch#2.6.1
Or, in package.json file , wrote "type": "module" etc.
Ref: Instead change the require of index.js, to a dynamic import() which is available in all CommonJS modules
Could anyone please help me to solve the error? Any help would be much appreciate.
Request: Please don't close the question. I know it's duplicate question, however I couldn't find any solution, tried how much I found.Thank you
I got the same error requiring node-fetch. The solution was
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

RollupJS library React Hook Error useState

I'm bulding a lib that allow to export react components to a nextjs application, at first time it works very well but when I started to check react hooks on that library it trigger a invalid hook error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
In order to solve issues like that on webpack and microbundle, I was using npm link for development, cause this error happen on production build, that was my reference https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react
This strategy don't work on rollup stack, I tried to link react and do some configs and nothing is working
that's my rollup.config.js
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
import external from 'rollup-plugin-peer-deps-external'
import { terser } from 'rollup-plugin-terser'
import styles from "rollup-plugin-styles";
const input = 'src/index.js'
const output = 'dist/index'
export default [
{
input: input,
external: ['react', 'react-dom'],
output: {
file: `${output}.modern.js`,
format: 'es',
},
plugins: [
external('./package.json'),
resolve(),
commonjs({
include: ['node_modules/**'],
}),
babel({
exclude: 'node_modules/**'
}),
styles(),
terser()
],
},
]
An that's my package.json
{
"name": "project",
"version": "0.0.17",
"description": "",
"private": true,
"main": "dist/index.js",
"module": "dist/index.modern.js",
"umd:main": "dist/index.umd.js",
"source": "src/index.js",
"engines": {
"node": ">=10"
},
"scripts": {
"prebuild": "rimraf dist",
"build": "rollup -c --environment BUILD:production",
"watch": "rollup -c --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"devDependencies": {
"#babel/core": "^7.12.3",
"#babel/preset-env": "^7.12.1",
"#babel/preset-react": "^7.12.1",
"#webpack-cli/init": "^1.0.2",
"babel-loader": "^8.1.0",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^5.0.0",
"html-loader": "^1.3.2",
"html-webpack-plugin": "^4.5.0",
"microbundle-crl": "^0.13.11",
"mini-css-extract-plugin": "^1.2.1",
"node-sass": "^4.14.1",
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"rimraf": "^3.0.2",
"rollup": "^2.32.1",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-peer-deps-external": "^2.2.4",
"rollup-plugin-postcss": "^3.1.8",
"rollup-plugin-sass": "^1.2.2",
"rollup-plugin-scss": "^2.6.1",
"rollup-plugin-styles": "^3.11.0",
"rollup-plugin-terser": "^6.1.0",
"rollup-plugin-uglify": "^6.0.4",
"sass-loader": "^10.0.4",
"source-map-loader": "^1.1.1",
"static-site-generator-webpack-plugin": "^3.4.2",
"style-loader": "^2.0.0"
},
"peerDependencies": {
"react": "17.0.1",
"prop-types": "15.7.2",
"react-dom": "17.0.1"
},
"dependencies": {
"file-loader": "^6.2.0"
}
}
When I change my nextjs application on dev mode removing a test useState component it works, but if I reload the page or load directly with a useState component rendered it will trigger a react hook error :(
I found the reason for my case.
It's necessary peerDependencies setting on the package.json file.
"peerDependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
So you try dependencies to peerDependencies.
"peerDependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"file-loader": "^6.2.0"
},
Hope this helps. :)

Getting error while jest: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables

Trying to run yarn test and have tried many version of node (8 and 11), react (57,58), but cannot fix this error.
FAIL __tests__/index.ios.js
● Test suite failed to run
/xyz/mobile-react/node_modules/react-native/jest/setup.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
Invalid variable access: MockNativeMethods
Whitelisted objects: Array, ArrayBuffer, Boolean, DataView, Date, Error, EvalError, Float32Array, Float64Array, Function, Generator, GeneratorFunction, Infinity, Int16Array, Int32Array, Int8Array, InternalError, Intl, JSON, Map, Math, NaN, Number, Object, Promise, Proxy, RangeError, ReferenceError, Reflect, RegExp, Set, String, Symbol, SyntaxError, TypeError, URIError, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray, WeakMap, WeakSet, arguments, expect, jest, require, undefined, console, DTRACE_NET_SERVER_CONNECTION, DTRACE_NET_STREAM_END, DTRACE_HTTP_SERVER_REQUEST, DTRACE_HTTP_SERVER_RESPONSE, DTRACE_HTTP_CLIENT_REQUEST, DTRACE_HTTP_CLIENT_RESPONSE, global, process, Buffer, clearImmediate, clearInterval, clearTimeout, setImmediate, setInterval, setTimeout.
Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with `mock` are permitted.
at invariant (node_modules/babel-jest/node_modules/babel-plugin-jest-hoist/build/index.js:13:11)
package.json:
{
"name": "XYZ",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"android-local": "ENVFILE=.env.local react-native run-android",
"android-dev": "ENVFILE=.env.dev react-native run-android",
"android-qa": "ENVFILE=.env.qa react-native run-android",
"build-android-dev": "export ENVFILE=.env.dev && cd android && ./gradlew assembleRelease && cd ..",
"build-android-qa": "export ENVFILE=.env.qa && cd android && ./gradlew assembleRelease && cd ..",
"test": "jest"
},
"rnpm": {
"assets": [
"./assets/fonts/"
]
},
"dependencies": {
"chai": "^4.1.2",
"chai-http": "^4.0.0",
"eslint-config-rallycoding": "^3.2.0",
"fs": "0.0.1-security",
"google-auth-library": "^0.11.0",
"googleapis": "^22.2.0",
"jetifier": "^1.6.4",
"lodash": "^4.17.4",
"moment": "^2.18.1",
"node-fetch": "^2.1.2",
"prop-types": "^15.5.10",
"q": "^1.5.0",
"react": "16.6.1",
"react-native": "0.58",
"react-native-android-location-enabler": "^1.0.5",
"react-native-android-location-services-dialog-box": "^2.0.0",
"react-native-config": "^0.6.1",
"react-native-datepicker": "^1.6.0",
"react-native-hockeyapp": "^0.5.3",
"react-native-image-crop-picker": "^0.16.0",
"react-native-image-resizer": "1.0.0",
"react-native-localization": "^0.2.1",
"react-native-maps": "^0.21.0",
"react-native-tab-view": "0.0.75",
"react-native-vector-icons": "6.1.0",
"react-native-version-number": "^0.1.2",
"react-navigation": "^1.0.0-beta.11",
"react-navigation-redux-helpers": "^1.0.3",
"react-redux": "^5.0.5",
"readline": "^1.3.0",
"redux": "^3.7.2",
"redux-persist": "^5.9.1",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"babel-jest": "20.0.3",
"babel-plugin-transform-object-rest-spread": "^7.0.0-beta.3",
"babel-preset-jest": "22",
"babel-preset-react-native": "4.0.1",
"jest": "20.0.4",
"mocha": "^5.1.1",
"react-test-renderer": "16.0.0-alpha.12"
},
"jest": {
"preset": "react-native"
}
}
.babelrc
{
"presets": ["react-native"]
}
Without seeing your exact code, it's hard to say what the problem is. However, the key is in the NOTE:
Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with mock are permitted.
The problem is that Jest mocks get hoisted to the top of the page. So, you can't reference a variable in your mocks... because the variable doesn't exist yet. See:
https://jestjs.io/docs/en/es6-class-mocks.html#calling-jestmock-docs-en-jest-object-jestmockmodulename-factory-options-with-the-module-factory-parameter
To overcome that, you need to do as the Note says, prefix your variable with the word "mock".
Here's an example where the import getAppPages needs to be overridden so that it returns a fake array (appPages)
import React from 'react';
import { getAppPages } from 'utils';
import App from './App';
import { fireEvent, render } from '../../../test/test-utils';
import appPages from '../../../__mocks__/data/appPages';
const mockAppPages = appPages;
jest.mock('utils', () => ({
getAppPages: () => mockAppPages,
}));
describe('App', () => {
test('renders and defaults to home page and matches snapshot', () => {
...
});
});

Using es7 functions with Babel

I would like to include es7 functions in my project to start using fetch await asynchronous way in it.
I'm using gulp, browserify and babelify (7.2.0), reading some docs I saw that the way to say babelify to use es7 functions is including this line to the babelify transform:
optional: ['runtime', 'es7.asyncFunctions']
So that my whole gulp task is as follows:
gulp.task('js',function(){
var bundleStream = browserify({
entries:[config.paths.mainJs],
debug: true,
transform: [babelify.configure({
presets:["es2015","react"],
optional: ['runtime', 'es7.asyncFunctions']
})]
}).transform("browserify-shim")
.bundle()
.on('error',console.error.bind(console))
bundleStream
.pipe(source('compiled.js'))
.pipe(buffer())
// .pipe(uglify())
.pipe(rename('compiled.min.js'))
.pipe(gulp.dest(config.paths.dist + '/js'))
});
Unfortunetely I'm getting the following error running the task:
"Unknown option: base.optional while parsing file:"
Googling a bit I saw that babelify 7.x does use babel 6.0 and apparently this parameter optional does not exist anymore in babel 6.0.
I don't want to downgrade my babelify version to make this work but instead I would like to include es7 functions with the version 7 of babelify, does someone know how to do it?
Any help would be very appreciated as there is no much info about it out there
Just in case, please find also my package.json file:
"dependencies": {
"bootstrap": "^3.3.5",
"history": "^1.13.0",
"jquery": "^2.1.4",
"jquery-ui": "^1.10.4",
"jquery.easing": "^1.3.2",
"moment": "^2.10.2",
"react": "^0.14.3",
"react-bootstrap": "^0.28.1",
"react-dom": "^0.14.3",
"react-router": "^1.0.2",
"reflux": "^0.3.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.1.18",
"babel-preset-react": "^6.1.18",
"babelify": "^7.2.0",
"browserify": "^9.0.8",
"browserify-shim": "^3.8.11",
"gulp": "^3.9.0",
"gulp-concat": "^2.6.0",
"gulp-connect": "^2.2.0",
"gulp-open": "^1.0.0",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^1.5.1",
"jest-cli": "^0.8.0",
"reactify": "^1.1.0",
"regenerator": "^0.8.42",
"streamify": "^0.2.5",
"uglify-js": "^2.4.20",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0",
"watchify": "^3.1.2"
},
"browser": {
"jquery": "src/main/webapp/js/libs/jquery-1.11.1.min.js",
"x": "./vendor/x.js"
},
"browserify": {
"transform": [
"browserify-shim"
]
},
"browserify-shim": {
"jquery": "$"
}
optional: ['runtime', 'es7.asyncFunctions']
was how you configure Babel 5. You are using Babel 6, so it would be
plugins: ['transform-runtime', 'transform-async-to-generator']
One thing to note is that configuring Babel via Babelify is not recommended. Instead, it is better to create an .babelrc file in the root of your application with JSON in it, e.g.
{
presets:["es2015","react"],
plugins: ['transform-runtime', 'transform-async-to-generator']
}
and npm install --save-dev babel-plugin-transform-runtime babel-plugin-transform-async-to-generator

Categories