I am using JSDOC and all it supported npm plugins to create nice documentation. Getting hard time when jsdoc is running and parsing JSX file it always throws error as below near = sign
SyntaxError: unknown: Unexpected token
export default class SaveDesign extends Component {
static displayName = 'SaveDesign';
}
conf.json file
{
"source": {
"include": [ "src/app/test.js", "src/app/components/Modals/Template/SaveDesign.jsx"],
"exclude": [ "src/fonts", "src/icons", "src/less", "src/vector-icon" ],
"includePattern": ".+\\.js(doc|x)?$",
"excludePattern": "(^|\\/|\\\\)_"
},
"plugins": ["node_modules/jsdoc-babel"],
"babel": {
"extensions": ["js", "es6", "jsx"],
"presets": ["es2015"]
},
"jsx": {
"extensions": ["js", "jsx"]
}
}
Class properties aren't part of the ES2015 spec, so they're not part of the ES2015 Babel preset either. The proposal to add class properties to the language is currently at Stage 3 of the standardization process, so you need the Stage 3 preset.
https://babeljs.io/docs/plugins/preset-stage-3/
Alternatively, you could just install the class properties plugin on its own:
https://babeljs.io/docs/en/babel-plugin-proposal-class-properties
As stage-2 , stage-3 or any other stage preset are removed in babel 7 or newer so you have to add plugin separately.
Please use "require()" for importing plugin otherwise it wont work.
Here is the .bablerc file -
module.exports = {
plugins: [
[require("#babel/plugin-proposal-class-properties"), { loose: false }]
],
presets: ["#babel/preset-env", "#babel/preset-react"]
};
#Joe thanks yes the plugin which you mentioned will help to solve the problem. In my case the way I solved it was by making sure to have all .babelrc dependency copied to jsdoc babel property as well I was missing this piece which was giving me all the errors.
Related
Project setup:
Vuejs 3
Webpack 4
Babel
TS
We created the project using vue-cli and add the dependency to the library.
We then imported a project (Vue Currency Input v2.0.0) that uses optional chaining. But we get the following error while executing the serve script:
error in ./node_modules/vue-currency-input/dist/index.esm.js
Module parse failed: Unexpected token (265:36)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| getMinValue() {
| let min = this.toFloat(-Number.MAX_SAFE_INTEGER);
> if (this.options.valueRange?.min !== undefined) {
| min = Math.max(this.options.valueRange?.min, this.toFloat(-Number.MAX_SAFE_INTEGER));
| }
I read that Webpack 4 doesn't support optional chaining by default. So, we added the Babel plugin for optional chaining. This is our babel.config.js file:
module.exports = {
presets: ["#vue/cli-plugin-babel/preset"],
plugins: ["#babel/plugin-proposal-optional-chaining"],
};
(But, if I am correct, this plugin is now enable by default in the babel-preset. So this modification might be useless ^^)
One thing that I don't understand is that we can use optional chaining in the .vue files.
I created a SandBox with all the files: SandBox
How could I solve this error?
I was able to overcome this issue using #babel/plugin-proposal-optional-chaining, but for me the only way I could get Webpack to use the Babel plugin was to shove the babel-loader configuration through the Webpack options in vue.config.js. Here is a minimal vue.config.js:
const path = require('path');
module.exports = {
chainWebpack: config => {
config.module
.rule('supportChaining')
.test(/\.js$/)
.include
.add(path.resolve('node_modules/PROBLEM_MODULE'))
.end()
.use('babel-loader')
.loader('babel-loader')
.tap(options => ({ ...options,
plugins : ['#babel/plugin-proposal-optional-chaining']
}))
.end()
}
};
NB replace "PROBLEM_MODULE" in the above with the module where you have the problem.
Surprisingly I did not need to install #babel/plugin-proposal-optional-chaining with NPM. I did a go/no-go test with an app scaffolded with #vue/cli 4.5.13, in my case without typescript. I imported the NPM module that has been causing my grief (#vime/vue-next 5.0.31 BTW), ran the serve script and got the Unexpected token error on a line containing optional chaining. I then plunked the above vue.config.js into the project root and ran the serve script again, this time with no errors.
My point is it appears this problem can be addressed without polluting one's development environment very much.
The Vue forums are in denial about this problem, claiming Vue 3 supports optional chaining. Apparently not, however, in node modules. A post in this thread by atflick on 2/26/2021 was a big help.
Had same issue with Vue 2 without typescript.
To fix this you need to force babel preset to include optional chaining rule:
presets: [
[
'#vue/cli-plugin-babel/preset',
{
include: ['#babel/plugin-proposal-optional-chaining'],
},
],
],
Can also be achieved by setting old browser target in browserslist config.
Most importantly, you need to add your failing module to transpileDependencies in vue.config.js:
module.exports = {
...
transpileDependencies: ['vue-currency-input],
}
This is required, because babel by default will exclude all node_modules from transpilation (mentioned in vue cli docs), thus no configured plugins will be applied.
I had a similar problem. I'm using nuxt but my .babelrc file looks like the below, and got it working for me.
{
"presets": [
["#babel/preset-env"]
],
"plugins":[
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
],
"env": {
"test": {
"plugins": [
["transform-regenerator", {
"regenerator": true
}],
"#babel/plugin-transform-runtime"
],
"presets": [
["#babel/preset-env", {
"useBuiltIns": false
}]
]
}
}
}
I managed to fix the solution by adding these lines to package.json:
...
"scripts": {
"preinstall": "npx npm-force-resolutions",
...
},
"resolutions": {
"acorn": "8.0.1"
},
...
I'm having a hard time trying to configure Babel to transpile code that IE11 can understand, specifically arrow functions. Running npx webpack --mode=development with my configuration doesn't convert the arrow functions in my code: in the eval() statement in the generated code, I can see that all the instances have gone unconverted.
Unlike in the console output quoted in this question, there's no mention in mine of "Using targets" or "Using presets". Whether that's something to do with using npx webpack rather than npm run build I don't know.
Here's the Babel part of my package.json:
{
// name, version etc. snipped
"devDependencies": {
"#babel/core": "^7.1.2",
"#babel/plugin-transform-async-to-generator": "^7.1.0",
"#babel/plugin-transform-es2015-arrow-functions": "^6.22.0",
"#babel/plugin-transform-es2015-modules-commonjs": "^6.26.2",
"#babel/preset-env": "^7.1.0",
"ajv": "^6.5.4",
"copy-webpack-plugin": "^4.5.2",
"eslint-plugin-jest": "^21.24.1",
"jest": "^23.6.0",
"jest-dom": "^2.0.4",
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2"
},
"babel": {
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": "11"
}
}
]
],
"env": {
"development": {
"plugins": [
"transform-es2015-arrow-functions",
"transform-es2015-modules-commonjs"
]
},
"test": {
"plugins": [
"transform-es2015-arrow-functions",
"transform-es2015-modules-commonjs"
]
}
}
}
}
My webpack.config.js looks like:
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
module.exports = {
entry: "./src/thing.js",
optimization: {
minimize: false
},
output: {
filename: "thing.js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new CopyWebpackPlugin([
// snipped
])
]
};
I arrived at this point from reading other questions here about Babel configurations, and the babel-preset-env docs and also the very skimpy babel-plugin-transform-es2015-arrow-functions docs. The answers to this very similar question (no accepted answer) don't mention that plugin at all, and one suggests using a polyfill, which seems to involve loading a library in your actual code rather than at this stage?
I'm very new to working with Webpack in general and don't understand what the difference is between "env" (which gets mentioned in a lot of questions) and "#babel/preset-env". Or really what the former implies in general; if you click on "env" in the docs navigation, it takes you to the page for #babel/preset-env.
What am I doing wrong?
If you are using Webpack 5, you need to specify the features that you want to transpile in the ouput.environment configuration, as explained here: https://webpack.js.org/configuration/output/#outputenvironment.
output: {
// ... other configs
environment: {
arrowFunction: false,
bigIntLiteral: false,
const: false,
destructuring: false,
dynamicImport: false,
forOf: false,
module: false,
},
}
EDIT 08/10/22
While doing some refactoring of my webpack configuration, I figured out that the arrows had stopped transpiling (or maybe I didn't test extensively when giving the original answer).
Two things weren't setup correctly: the target key was missing, and the babel configuration had a wrong value.
For supporting legacy browsers, the target key needs to be set like this:
target: ['web', 'es5']
While in the Babel configuration, I had added 'not dead' in the browserslist configuration under targets in the Babel loader, so since IE11 is now technically dead, this configuration removed the trasnpilation of the arrow function.
So if you still need to transpile the arrow function, this would be the relevant part in the Babel configuration.
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: 'babel-loader',
options: {
presets: [
[
'#babel/preset-env',
{
useBuiltIns: 'entry',
targets: {
// be sure not to add 'not dead' here
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']
},
corejs: {
version: 3,
proposals: false,
},
},
],
],
plugins: [['#babel/plugin-transform-runtime', { corejs: 3 }]],
},
},
},
],
},
In addition to loganfsmyth's answer that solved the problem, I want to note for any other beginners reading this that I made life easier for myself afterward by moving the Babel configuration out of package.json into a .babelrc.
I also discovered that the plugins I needed, such as the one I mentioned above, babel-plugin-transform-es2015-arrow-functions, have newer versions with a different naming scheme - for that example, #babel/plugin-transform-arrow-functions. The documentation pages for the old versions don't mention that.
The module part of my webpack.config.js now looks like:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
My .babelrc looks like:
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": "11"
},
"useBuiltIns": "entry"
}
]
],
"plugins": [
"#babel/transform-async-to-generator",
"#babel/transform-arrow-functions",
"#babel/transform-modules-commonjs"
],
"env": {
"development": {},
"test": {},
"production": {}
}
}
Update 2021: As of Webpack version 5, it outputs ES6 code by default. If you need that not to happen, you need to add a configuration setting. See Giorgio Tempesta's answer.
Babel itself is a transformation library, but on its own it will not integrate into any specific tooling. To use Babel with Webpack, you'll want to install the babel-loader package and configure it in your Webpack config using something along the lines of
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
}
}
]
}
I had the same problem. Turned out it wasn't all of my code that had arrow functions, but only one single library. I went inside my built bundle, and searched for code with arrow functions (=>). Then I searched and copied some unique-looking names around it and managed to find the source of it searching for it in all files within node_modules. In my case it turned out that the code with arrow functions came from fetch polyfill called unfetch. I'm not sure why it didn't get transpiled by the plugin, but I switched it to "whatwg-fetch" and it worked just fine - no arrow functions in bundle anymore. You could try the same technique to discover what causes it in your case.
2022 Update
If you have this problem now, it could be because browerslist treats IE 11 as dead since version 4.21.0. The solution to access IE 11 anyway is to add ie 11 either as the last entry in browserslist or at least after not dead.
Normally you don't see browserslist in the package.json, but if you use npm ls browserslist you can see which dependency uses browserslist and which version of it.
See also: https://github.com/browserslist/browserslist/issues/699
I learnt how to use promises in a browser but when I want to use it in my node.js it throw error.
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url) {
^
ReferenceError: regeneratorRuntime is not defined
node version
v10.4.1
I use babel for export and import syntax with settings like here in starting file
require('babel-register')({
presets: [ 'env' ]
})
babel-polyfill is required. You must also install it in order to get async/await working.
Here explain better Babel 6 regeneratorRuntime is not defined
I was unable to use async/await and for me this worked out.
In your babel file include this.
presets: [
[
"#babel/preset-env",
{
"targets": {
"node": "10"
}
}
] ]
Presumably you are trying to use async / await syntax? You will need to install transform-async-to-generator plugin and include it in your Babel config
require('babel-register')({
presets: ['env'],
plugins: ['transform-async-to-generator']
})
Our app imports files using import ES2015 style syntax, utilizing Webpack 4.6.0 native support for ES2015 modules. We also use an alias to shorten our relative file paths.
Webpack.conf.js
resolve: {
extensions: ['.js', '.json', '.less'],
alias: {
'#': resolve('public/js'),
'handlebars': 'handlebars/dist/handlebars.js',
},
modules: ['less', 'node_modules']
},
example.js
import widget from '#/widgets/widget';
file structure
- webpack.conf.js
- .babelrc
- test/
- public/
- - js/
- - - widgets/
- - - - widget.js
When I imported for example example.js, which has an alias'd import, Jest would throw an error, "cannot resolve module '#/widgets/widget'.
According to a remarkably specific article as well as the Jest documentation, the solution is to use Jest's ModuleNameMapper config property to set up matching alias'. I have attempted to do so:
package.json
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"#(.*)$": "<rootDir>/public/js/$1"
},
"verbose": true,
"transform": {
"^.+\\.js$": "babel-jest"
},
"globals": {
"NODE_ENV": "test"
},
"moduleFileExtensions": [
"js"
],
"moduleDirectories": [
"node_modules"
]
},
As well as properly configure babel:
.babelrc
{
"presets": [
[
"env",
{
"modules": false,
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
],
"es2015",
"stage-2"
],
"plugins": [
"syntax-dynamic-import"
]
}
Now, when I run Jest (with the --no-cache flag just in case), I get this error:
test/test.test.js
● Test suite failed to run
Configuration error:
Could not locate module #babel/code-frame (mapped as /home/calebjay/Documents/ide/public/js/babel/code-frame)
Please check:
"moduleNameMapper": {
"/#(.*)$/": "/home/calebjay/Documents/ide/public/js/$1"
},
"resolver": undefined
I can't find #babel/code-frame anywhere outside of package-lock.json, and just for giggles I stripped all mentions of #{{anything}} from there and ran tests again, same result.
Is jest stepping over babel somehow? How can I get my tests to run with Jest using aliases?
EDIT: To try to narrow down what is calling #babel/code-frame, I tried deleting es2015 and stage-2 from .babelrc, to no effect. I tried deleting the transform property of the Jest config in package.json, to no effect. I tried deleting the env.test.plugins property from .babelrc, to no effect. Same error.
EDIT2: Thinking maybe some other package is requiring it, I checked package.json. It seems jest-message-util requires #babel/code-frame. I do see #babel/code-frame in my node_modules though... so perhaps the problem is that jester is saying "ok, all instances of #, turn into public/js" ?
"#(.*)$": "<rootDir>/public/js/$1"
will convert #babel/code-frame to
"<rootDir>/public/js/babel/code-frame"
which doesn't exist. You need to make your pattern more specific and do
"#/(.*)$": "<rootDir>/public/js/$1"
Note the additional / at the beginning. That way it will still match your #/widgets/widget, but it won't match other scoped packages.
I'm onto my personal project and I want to integrate flowtype. Now, within the package.json I got:
"babel-plugin-syntax-flow": "6.3.13"
which helps babelify to transcript the flowtype's syntax but it doesn't do 'flow check' and doesn't log potential errors. Should I setup a separate gulp task with a separate package for it like https://www.npmjs.com/package/gulp-flowtype or should the the babel-plugin-syntax-flow also handle error logging?
The only thing Babel knows about Flow is how to parse it so that it won't cause a syntax error. Generally you'd use babel-plugin-transform-flow-strip-types, which enables the syntax plugin you have now, and then deletes the flow types so they don't end up in your final output. This is also enabled by default if you use the Babel preset react.
You'd definitely still have to use Flow's standard typechecker to do the actual static analysis.
Here is my working solution:
You need to install:
$ npm i --save-dev babel-plugin-syntax-flow
babel-plugin-transform-flow-strip-types babel-plugin-typecheck
Then add
"typecheck",
"syntax-flow",
"transform-flow-strip-types",
to your .babelrc configuration
Here is a sample of my configuration:
{
"presets": ["stage-2", "es2015", "react"],
"plugins": [
"react-hot-loader/babel",
"transform-decorators-legacy",
"typecheck",
"syntax-flow",
"transform-flow-strip-types",
"transform-async-to-generator"
],
"env": {
"development": {
"presets": ["react-hmre"]
},
"test":{
"presets": ["stage-2", "es2015", "react"],
"plugins": [
"react-hot-loader/babel",
"transform-decorators-legacy",
"typecheck",
"syntax-flow",
"transform-flow-strip-types",
"transform-async-to-generator"
],
}
}
}
This will output errors both at runtime and into your console.
As of June 2017, all you need to do is npm i --save-dev flow-runtime and add:
{
"plugins": [["flow-runtime", {
"assert": true,
"annotate": true
}]]
}