nyc coverage reports empty with babel mocha - javascript

I am using mocha to unit test my js code which is using babel also. I am using nyc to do coverage. But in the end, the result is showing empty.
Why does it show All files 0 even though my test file is requiring redux.js and number-reducer.js files ?
my test script inside package.json is
{
...
"scripts": {
...
"test": "cross-env NODE_ENV=test npm run lint && nyc --reporter=lcov --reporter=text mocha",
"coverage": "nyc report --reporter=text-lcov | coveralls"
},
...
"devDependencies": {
"#babel/core": "~7.3.4",
"#babel/preset-env": "~7.3.4",
"#babel/register": "~7.0.0",
"babel-loader": "~8.0.5",
"babel-plugin-istanbul": "~5.1.1",
"babel-polyfill": "~6.26.0",
"chai": "~4.2.0",
...
"cross-env": "~5.2.0",
"eslint": "~5.15.0",
"mocha": "~6.0.0",
"nyc": "~13.3.0",
...
"webpack": "~4.29.4",
"webpack-cli": "~3.2.1"
},
"nyc": {
"require": [
"#babel/register"
],
"reporter": [
"lcov",
"text"
],
"sourceMap": false,
"instrument": false
}
}
My .babelrc file is
{
"presets": [
"#babel/preset-env"
],
"env": {
"test": {
"plugins": ["istanbul"]
}
}
}
My test.spec.js file is
import chai from "chai";
let redux = require("../src/js/redux").redux;
let NumberReducer = require("../src/js/number-reducer").NumberReducer;
const expect = chai.expect;
describe("ReduxModule", function () {
it('should expect an object', function () {
const ReduxModule = redux(NumberReducer);
expect(ReduxModule).to.be.a("object");
});
describe('ReduxModule#getState', function () {
it('should give me zero', function () {
const ReduxModule = redux(NumberReducer);
expect(ReduxModule.getState()).to.equal(0);
});
...
});
});

Related

Using Async causing: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module asyncToGenerator.js

I have a problem with "async" in babel and node js that i couldn't solve for days... the error bellow:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\BOOSTACKSTICK\BOOSTACK\node_modules\#babel\runtime\helpers\esm\asyncToGenerator.js [1] require() of ES modules is not supported. [1] require() of C:\BOOSTACKSTICK\BOOSTACK\node_modules\#babel\runtime\helpers\esm\asyncToGenerator.js from C:\BOOSTACKSTICK\BOOSTACK\prod-server\api\auth\auth-controller.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. [1] Instead rename asyncToGenerator.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\BOOSTACKSTICK\BOOSTACK\node_modules\#babel\runtime\helpers\esm\package.json.
I compile my dev-server folder to a prod-server with config bellow
package.json
"scripts": {
"serve": "vue-cli-service serve",
"build": "babel dev-server --out-dir prod-server && vue-cli-service build",
"lint": "vue-cli-service lint",
"dev": "concurrently \"babel dev-server --out-dir prod-server --watch\" \"nodemon prod-server/index.js\" \"npm run serve\" "
},
"devDependencies": {
"#babel/cli": "^7.12.1",
"#babel/core": "^7.12.3",
"#babel/node": "^7.12.1",
"#babel/plugin-transform-async-to-generator": "^7.12.1",
"#babel/plugin-transform-runtime": "^7.12.1",
"#babel/preset-env": "^7.12.1",
"#babel/runtime-corejs3": "^7.12.1",
"#vue/cli-plugin-babel": "^4.5.8",
"#vue/cli-plugin-eslint": "^4.5.8",
"#vue/cli-service": "^4.5.8",
"babel-eslint": "^10.1.0",
"compass-mixins": "^0.12.10",
"concurrently": "^5.3.0",
"core-js": "^3.6.5",
"css-loader": "^3.6.0",
"eslint": "^5.16.0",
},
.babelrc
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "usage", // or "entry"
"corejs": 3,
"targets": {
"node": "current"
}
}
]
],
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"corejs": 3
}
],
["#babel/plugin-proposal-class-properties"]
]
}
Environment
Node: v12.16.3
Babel: 7.12.3
**Simple code with "async" that causing a problem **
export async function index(req, res) {
return res.status(200).json({ user: "user" });
}
** Babel Output**
"use strict";
var _interopRequireDefault = require("C:/BOOSTACKSTICK/BOOSTACK/node_modules/#babel/runtime/helpers/interopRequireDefault");
var _Object$defineProperty = require("#babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.index = index;
var _regenerator = _interopRequireDefault(require("#babel/runtime-corejs3/regenerator"));
require("regenerator-runtime/runtime");
var _asyncToGenerator2 = _interopRequireDefault(require("C:/BOOSTACKSTICK/BOOSTACK/node_modules/#babel/runtime/helpers/esm/asyncToGenerator"));
//Check And Validate Request (LOGIN METHODE)
function index(_x, _x2) {
return _index.apply(this, arguments);
}
function _index() {
_index = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(req, res) {
return _regenerator.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", res.status(200).json({
user: "user"
}));
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _index.apply(this, arguments);
}
Possible Solution
the only workaround i tested to avoid this error is to modify manually the node_modules\#babel\runtime\helpers\esm\package.json to remove "type": module and remove import from node_modules\#babel\runtime\helpers\esm\asyncToGenerator.js
is it a bug or i'm doing something wrong?
Thank you in advance for your reply.

Why babel-watch can compile and run my code but babel doesn't?

I've got a strange situation and I hope there is someone to help me and explain why it happens.
Working on the code I used babel-watch and everything was just fine until I faced the moment I needed just to compile the code into a "dist" folder so as to be able to run it on Heroku.
I cannot run the code, but it's compiled successfully, and anyway I get different errors like:
uncaughtException: Unexpected token :\nC:\\Users\\Валерий\\Documents\\Projects\\cocoon-api\\dist\\environment\\development.js.map:1\n{\"version\":3,\"sources\":[\"../../src/environment/development.js\"],\"names\":[\"dotenv\",\"config\",\"development\",\"port\",\"process\",\"env\",\"PORT\",\"db\",\"username\",\"DB_USER\",\"password\",\"DB_PASSWORD\",\"name\",\"DB_NAME\",\"token_secret\",\"TOKEN_SECRET\",\"hash_rounds\",\"HASH_ROUNDS\",\"log_level\",\"mail\",\"host\",\"MAIL_HOST\",\"MAIL_PORT\",\"secure\",\"MAIL_SECURE\",\"user\",\"MAIL_USER\",\"pass\",\"MAIL_PASS\",\"dev\",\"sub\",\"general\",\"key\"],\"mappings\":
If it didn't work with babel-watch I would think that's something with the code but since it does work in a development mode I assume that's a problem with a compiler - Babel.
If anyone knows how to setup it properly so it works I would be very thankful!
project.json
{
"name": "cocoon-api",
"version": "1.0.0",
"description": "",
"private": true,
"main": "src/server.js",
"scripts": {
"clean": "rm -rf dist",
"build": "babel ./src --out-dir ./dist --source-maps",
"prod": "node ./dist/server.js",
"start": "set NODE_ENV=production&&npm-run-all clean build prod",
"old:start": "set NODE_ENV=production&&babel-watch src/server.js",
"old:dev": "babel-watch src/server.js",
"compile": "rm -rf dist && babel src --out-dir dist"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#babel/polyfill": "^7.8.7",
"apollo-server-express": "^2.9.14",
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"graphql": "^14.5.8",
"graphql-depth-limit": "^1.1.0",
"graphql-iso-date": "^3.6.1",
"graphql-middleware": "^4.0.2",
"graphql-shield": "^7.0.6",
"graphql-tag": "^2.10.1",
"graphql-toolkit": "^0.7.5",
"graphql-tools": "^4.0.6",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.15",
"merge-graphql-schemas": "^1.7.4",
"mongoose": "^5.8.3",
"nodemailer": "^6.4.4",
"npm-run-all": "^4.1.5",
"password-validator": "^5.0.3",
"simple-crypto-js": "^2.2.0",
"validator": "^12.2.0",
"winston": "^3.2.1"
},
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.8.7",
"#babel/node": "^7.7.7",
"#babel/preset-env": "^7.8.7",
"babel-plugin-import-graphql": "^2.7.0",
"babel-watch": "^7.0.0",
"dotenv": "^8.2.0",
"nodemon": "^2.0.2"
}
}
file mentioned in the error
// require('dotenv').config();
import dotenv from 'dotenv';
dotenv.config();
export const development = {
port: process.env.PORT || 3000,
db: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
name: process.env.DB_NAME,
},
token_secret: process.env.TOKEN_SECRET,
hash_rounds: process.env.HASH_ROUNDS,
log_level: 'info',
mail: {
host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT,
secure: process.env.MAIL_SECURE,
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS
},
development: 'test',
dev: { sub: 'test' },
general: { key: 'value' }
};
// console.log(development);
// module.exports = development;
babel config
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "current"
},
"useBuiltIns": "usage"
}
]
]
}
entry point
import { env } from "./environment";
import { apiExplorer } from "./graphql";
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { database } from "./utils/database";
import { logger } from "./utils/logging";
import { verify } from "./utils/jwt";
import confirmRoute from './routes/confirm';
import test from './routes/test';
database.init();
apiExplorer.getSchema().then((schema) => {
// Configure express
const port = env.PORT;
const app = express();
app.use('/confirm', confirmRoute);
app.use('/', test);
// Configure apollo
const apolloServer = new ApolloServer({
schema,
context: ({ req, res }) => {
const context = [];
// verify jwt token
context.authUser = verify(req, res);
return context;
},
formatError: (error) => {
logger.error(error);
return error;
},
debug: true
});
apolloServer.applyMiddleware({ app });
app.listen({ port }, () => {
logger.info(`🚀Server ready at http://localhost:${port}${apolloServer.graphqlPath}`);
});
})
.catch((err) => {
logger.error('Failed to load api at : ', err);
})

Jest cannot find module sometimes

actually i'm trying to test a function and getting that error:
Files that i'm using:
searchUserService
import { SearchUserService } from '../../src/service/searchUser.service';
import { SearchUserRepository} from '../../src/repository/searchUser.repository'
import { Util } from 'src/util/util'
let userId = '123456'
describe('', () => {
it('', async () =>{
const res = new SearchUserService(new SearchUserRepository(new Util)).searchCredential(userId)
expect(res).toBe('')
})
})
package.json
{
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nodemon",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "tslint -p tsconfig.json -c tslint.json",
"test": "node_modules/.bin/jest --config jest.conf.js --detectOpenHandles",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "6.7.2",
"#nestjs/core": "6.7.2",
"#nestjs/platform-express": "6.7.2",
"axios": "0.19.2",
"lodash": "4.17.15",
"reflect-metadata": "0.1.13",
"rimraf": "3.0.0",
"rpc-proxy": "^1.0.7",
"rxjs": "6.5.3",
"swagger-ui-express": "4.1.3",
"typescript": "3.6.3"
},
"devDependencies": {
"#nestjs/cli": "6.9.0",
"#nestjs/schematics": "6.7.0",
"#nestjs/swagger": "4.2.7",
"#nestjs/testing": "6.7.1",
"#types/express": "4.17.1",
"#types/jest": "24.0.18",
"#types/node": "12.7.5",
"#types/supertest": "2.0.8",
"dotenv": "8.2.0",
"jest": "24.9.0",
"nodemon": "2.0.2",
"prettier": "1.18.2",
"supertest": "^4.0.2",
"ts-jest": "24.1.0",
"ts-node": "8.4.1",
"tsconfig-paths": "3.9.0",
"tslint": "5.20.0",
"yamljs": "0.3.0"
}
}
searchUser.service.ts
import { Injectable } from '#nestjs/common';
import { BaseService } from '********************';
import { SearchUserRepository } from '../repository/searchUser.repository';
#Injectable()
export class SearchUserService extends BaseService {
constructor(private readonly searchUserRepository: SearchUserRepository) {
super();
}
async searchCredential(userId: string) {
this.logger.info(`[SearchUserService] - searchCredential - userId = ${userId}`, '');
return await this.searchUserRepository.searchCredential(userId);
}
}
jest.conf.js
const path = require('path');
module.exports = {
rootDir: path.resolve(__dirname, './'),
verbose: true,
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverage: true,
coverageDirectory: process.env.JEST_CLOVER_OUTPUT_DIR || './_devops/coverage',
coverageReporters: ['text', 'clover', 'lcov'],
collectCoverageFrom: [
'**/src/**/*.{ts}',
'!**/spec/**/*.{ts}',
'!**/tests/**/*.{ts}',
],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'json',
'jsx'
]
};
I've tried with another functions and debug, when i start the debug, the error instantly happens doesn't give any chance, with another functions I get the same.
it appears to be an Import error from Jest or NestJs.
I've checked the documentation of Jest and some Issues that appears to be same as i'm getting, but non of them resolved my problem.

Plugin/Preset files are not allowed to export objects, only functions. Removing and keeping babel installs? Selection with webpack?

I'm trying to learn how to write a React App and set up from practically scratch.
I keep trying to run webpack --config webpack.dev.config.js.
I keep getting this error. And I've tried using different loaders and presets.
What is wrong with my setup? Is it my npm node modules are outdated?
I've tried updating all my presets, loaders and even babel itself.
Error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Plugin/Preset files are not allowed to export objects, only functions. In /Users/kyle.calica-steinhil/Code/react-components/react-imgur-album/node_modules/babel-preset-es2015/lib/index.js
at createDescriptor (/Users/kyle.calica-steinhil/Code/react-components/react-imgur-album/node_modules/#babel/core/lib/config/config-descriptors.js:178:11)
at items.map (/Users/kyle.calica-steinhil/Code/react-components/react-imgur-album/node_modules/#babel/core/lib/config/config-descriptors.js:109:50)
at Array.map (<anonymous>)
webpack.dev.config.js:
var path = require('path');
module.exports = {
mode: 'development',
// context: path.resolve(__dirname, 'src'),
entry: path.resolve(__dirname,'src/index.js'),
output: {
filename: 'main.js',
libraryTarget: "commonjs2"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015','react'],
plugins: ['transform-class-properties']
}
}
]
}
]
},
resolve: {
extensions: ['.js']
}
};
package.json :
{
"name": "react-imgur-album",
"version": "0.0.1",
"description": "React Component for displaying images in an Imgur Album",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.dev.config.js --progress --display-error-details"
},
"keywords": [
"imgur",
"react",
"react-components",
"component",
"images",
"photos",
"pics"
],
"author": "Kyle Calica",
"license": "ISC",
"dependencies": {
"#babel/preset-react": "^7.0.0",
"react-dom": "^16.5.2"
},
"devDependencies": {
"#babel/cli": "^7.1.2",
"#babel/core": "^7.1.2",
"#babel/plugin-proposal-class-properties": "^7.1.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"eslint": "^5.7.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-react": "^7.11.1",
"fixed": "^0.3.0",
"it": "^1.1.1",
"path": "^0.12.7",
"react": "^16.5.2",
"webpack": "^4.22.0",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.9"
}
}
index.js:
import React, { Component } from 'react';
var imgurAPI = 'https://api.imgur.com/3/album/';
export default class ImgurAlbum extends Component {
constructor(props){
super(props);
this.state = {
imgurPosts: [],
isLoading: true
};
}
componentDidMount(){
fetch(imgurAPI + this.props.album + '/images',{
'headers':{
'Authorizathion': 'client-id'
}
}).then(res => res.json())
.then(data => console.log(data));
}
render(){
return(
<div>
<h1>hi!</h1>
</div>
);
}
}
I notice I have two babel cores installed, I don't know how to remove one, or which one to keep. Or even how to select which one with webpack?
I found my solution!
It's a babel mismatch.
I had an old babel-core and babel-presets installed.
In Babel 7, it is best to install using:
npm i #babel/preset-react #babel/preset-env
then in your .babelrc:
{
"presets" : ["#babel/preset-env","#babel/preset-react"]
}
I also uninstalled the old babel-preset-react and babel-preset-es2015 for safe measure.
Still learning so I might be missing steps or understanding here. Please add if you believe you need more information or if I am wrong about anything, but I was able to get mine to build

why webpack does not like this expression

I tried to build my reactjs app using webpack and babel.
I started this app from react starter which comes with react-scripts build which worked before. However, it's a black box and didn't really provide all the features I need, especially when it comes to that a module doesn't like UglifyJS.
My webpack.config.js looks like this which is pretty simple:
var path = require('path');
var webpack = require('webpack');
var BUILD_DIR = path.resolve(__dirname, 'build_webpack');
var APP_DIR = path.resolve(__dirname, 'src');
module.exports = {
entry: APP_DIR + '/index.js',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
]
}
}
and I have this config in my package.js:
"scripts": {
"start": "react-scripts start",
"reactbuild": "react-scripts build",
"webpackbuild": "webpack --watch",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
Also my .babelrc file only has this:
{
"presets" : ["es2015", "es2016", "react"]
}
However, the code that worked in react-scripts build failed here, and the error output says:
ERROR in ./src/Pages/SearchTool/SearchResult.js
Module build failed: SyntaxError: Unexpected token (100:13)
(the error is referring to the data input argument)
renderChip = (data) => {
return (
<Chip
key={data.key}
I don't really see what is so special about this expression. I don't think this is very commonly used but should be legal though. Also, one reason that I switched to webpack was that the previous react build doesn't like es6, but one of my module which is important is written in es6.
I wonder what was missing in my config or other places. Thanks for all the help!
Edit:
my package.js:
{
"name": "myCoolApps",
"version": "0.1.0",
"private": true,
"devDependencies": {
"css-loader": "^0.26.1",
"react-scripts": "0.7.0",
"webpack": "^1.13.3"
},
"dependencies": {
"ace": "git+https://github.com/ajaxorg/ace.git#master",
"antd": "^2.7.2",
"axios": "^0.15.3",
"babel-core": "^6.24.1",
"babel-loader": "^6.4.1",
"babel-preset-env": "^1.4.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2016": "^6.24.1",
"babel-preset-react": "^6.24.1",
"card": "^2.2.1",
"card-react": "^1.2.6",
"chat-template": "0.0.22",
"codemirror": "^5.25.0",
"credit-card-type": "^5.0.1",
"css-loader": "^0.26.1",
"d3": "^4.7.4",
"firechat": "^3.0.1",
"firepad": "^1.4.0",
"flux": "^3.1.0",
"gulp": "^3.9.1",
"gulp-sass": "^3.1.0",
"history": "^1.17.0",
"little-loader": "^0.2.0",
"lodash": "^4.17.4",
"material-ui": "^0.16.6",
"moment": "^2.17.1",
"node-sass": "^4.5.0",
"quill": "^1.2.3",
"rc-calendar": "^7.6.5",
"react": "^15.5.4",
"react-autosuggest": "^7.0.1",
"react-cookie": "^1.0.4",
"react-credit-card": "^0.20.0",
"react-dom": "^15.5.4",
"react-dropzone": "^3.8.0",
"react-event-timeline": "^1.2.2",
"react-infinite": "^0.10.0",
"react-infinite-scroller": "^1.0.7",
"react-list": "^0.8.3",
"react-notification-system": "^0.2.12",
"react-router": "^3.0.0",
"react-tap-event-plugin": "^2.0.1",
"seedrandom": "^2.4.2",
"simplewebrtc": "^2.2.2",
"style-loader": "^0.13.1",
"superagent": "^3.3.1",
"webpack": "^1.15.0",
"y-array": "^10.0.6",
"y-indexeddb": "^8.1.9",
"y-leveldb": "0.0.1",
"y-map": "^10.0.5",
"y-memory": "^8.0.8",
"y-richtext": "^9.0.8",
"y-text": "^9.3.2",
"y-webrtc": "^8.0.7",
"y-websockets-client": "^8.0.15",
"yjs": "^12.1.7"
},
"scripts": {
"start": "react-scripts start",
"reactbuild": "react-scripts build",
"webpackbuild": "webpack",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
UPDATE:
I tried the env preset, and now my webpack.config.js looks like this:
{
"presets":
[
"react",
[
"env",
{
"targets": {
"uglify": false,
"node": "current",
"debug": true,
},
}
],
],
}
However, it still complains about this expression:
ERROR in ./src/Pages/SearchTool/SearchResult.js
Module build failed: SyntaxError: Unexpected token (100:13)
98 | }
99 |
> 100 | renderChip = (data) => {
| ^
101 | return (
102 | <Chip
103 | key={data.key}
# ./src/Pages/Connections/Connections.js 43:20-57
The function originally looks like this in the program (Note: it is inside a class):
renderChip = (data) => {
return (
<Chip
key={data.key}
onRequestDelete={this.handleRequestDelete}
style={{
borderRadius: '6px',
margin: '0 4px',
height: 35
}}
>
{data.label}
</Chip>
);
}
And also I tried include plugins manually
The place this function in my class looks like:
class Name extends Component {
constructor(props) {...}
renderChip = (data) => {
return (
<Chip
key={data.key}
onRequestDelete={this.handleRequestDelete}
style={{
borderRadius: '6px',
margin: '0 4px',
height: 35
}}
>
{data.label}
</Chip>
);
}
render() {...}
}
I manually included transform-es2015-function-name and transform-es2015-arrow-functions, but they didn't work. Are there some other plugins I need to include manually? Or is it caused by some other reason?
Solved
The solution is changing the function experssion to:
renderChip() {
...
}
Please add babel-preset-env package.
Your .babelrc should look something like this: (["env" ...] part is important here)
{
"presets": [
["env", {
"targets": {
"uglify": true,
"node": "current"
}
}]
]
}
Reading the docs I mentioned above. UglifyJS does not support ES6. It is recommended to use babel-minify instead.
UglifyJS does not currently support any ES6 syntax, so if you are
using Uglify to minify your code, targeting later browsers may cause
Uglify to throw syntax errors.
To prevent these errors - specify the uglify option, which will enable
all plugins and, as a result, fully compile your code to ES5. However,
the useBuiltIns option will still work as before, and only include the
polyfills that your target(s) need.
UPDATE:
Try installing/reinstalling these packages. you may not need all of them, but you may find use in them later on.
npm install --save-dev babel-core babel-loader babel-polyfill babel-preset-env babel-register babel-plugin-syntax-dynamic-import babel-plugin-transform-object-rest-spread babel-plugin-transform-regenerator
Write
renderChip(data) {
instead of
renderChip = (data) => {
You can't declare class methods with assignment operator directly in class body, instead you can do following.
renderChip(data) {
return (
<Chip
key={data.key}
onRequestDelete={this.handleRequestDelete}
style={{
borderRadius: '6px',
margin: '0 4px',
height: 35
}}
>
{data.label}
</Chip>
);
}
You can read about ES6 classes here.
Hope this helped!

Categories