“Export Default” in React Native Typescript causing Parsing Syntax Error

Asked
Active3 hr before
Viewed126 times

8 Answers

exportdefaulttypescriptcausingparsingsyntaxnativeerrorreact
90%

I am new to Typescript, and have recently begun a new React Native project where I'm running into an issue upon transpiling that causes the code to return this error in my simulator when running a build:, Does this sentence make sense for a native speaker? "the real Jones is living in a cave!" , Podcast 371: Exploring the magic of instant python refactoring with Sourcery ,So the solution came down to my beginner level understanding of Typescript and it how it transpiles.

The issue seems to be stemming from using export default in Typescript to export my component (happens both with or without connection to the Redux store), which when transpired into plain js is identified as a parsing error. When using export without the default keyword and importing the deconstructed component it behaves as it should. Here is the .tsx file where it is exported:

import * as React from 'react';
import { useState } from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';
import { ThunkDispatch } from 'redux-thunk';
import { fetchUser } from '../store/actions/user';
import { AppActions } from '../store/types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { User } from '../store/types/user';
import { AppState } from '../store';

interface Params {
  methodName: string;
  serviceName: string;
  params: string[];
}

interface ChildProps {
  setIsLoggedIn: any;
}

type Props = LinkDispatchProps & LinkStateProps & ChildProps;

export const LoginWindow: React.FC<Props> = props => {
  const [userName, onChangeUserName] = useState<string>('');
  const [pwd, onChangePwd] = useState<string>('');

  const params: Params = {
    methodName: 'string1',
    serviceName: 'string2',
    params: [userName, pwd],
  };

  const attemptLogin = async (): Promise<void> => {
    await props.fetchUser(params);
    if (props.user) {
      props.setIsLoggedIn(true);
    }
  };

  return (
    <View>
      <Text>Username:</Text>
      <TextInput
        style={styles.textField}
        onChangeText={onChangeUserName}
        value={userName}
        textContentType="username"
      />
      <Text>Password:</Text>
      <TextInput
        style={styles.textField}
        onChangeText={onChangePwd}
        value={pwd}
        textContentType="password"
        secureTextEntry={true}
      />
      <Button title="Log In" onPress={attemptLogin}>
        Log In
      </Button>
    </View>
  );
};

const styles = StyleSheet.create({
  textField: {
    height: 25,
    width: 200,
    borderStyle: 'solid',
    borderWidth: 1,
    borderColor: '#000',
  },
});

interface LinkStateProps {
  user: User;
}

interface LinkDispatchProps {
  fetchUser: (params: Params) => void;
}

const mapStateToProps = (state: AppState) => ({
  user: state.user,
});

const mapDispatchToProps = (
  dispatch: ThunkDispatch<any, any, AppActions>,
): LinkDispatchProps => ({
  fetchUser: bindActionCreators(fetchUser, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(LoginWindow);
load more v
88%

class MyClass1 {}
class MyClass2 {}
module.exports = {
   MyClass1,
   MyClass2
}
72%

This is how C:\study\reactodo\node_modules\react-icons\fa\angle-down.js looks like:,another-todo@0.1.0 test C:\study\reactodo node scripts/test.js --env=jsdom,I use react-icons in my component and when I try to render it with react-test-render I get this:, Sorry, something went wrong.

C:\study\reactodo\node_modules\react-icons\fa\angle-down.js:5
export default class FaAngleDown extends React.Component {
^^^^^^
SyntaxError: Unexpected token export

at transformAndBuildScript (node_modules\jest-runtime\build\transform.js:284:10)
at Object.<anonymous> (src\components\category\category.component.js:2:44)
   at Object.<anonymous> (src\components\category-tree\category-tree.component.js:4:184)

      Test Suites: 1 failed, 1 total
      Tests: 0 total
      Snapshots: 0 total
      Time: 6.59s
      Ran all test suites related to changed files.

      Watch UsagePress a to run all tests.
      › Press o to only run tests related to changed files.
      › Press p to filter by a filename regex pattern.
      › Press q to quit watch mode.
      › Press Enter to trigger a test run.`
load more v
65%

TypeScript will parse it as the following JavaScript:,Prior to TypeScript 2.4, in the following example,Will generate the following JavaScript output:,In TypeScript 3.4 and prior, the following example would fail:

If your functions are only able to handle string named property keys, use Extract<keyof T, string> in the declaration:

tsfunction useKey<T, K extends Extract<keyof T, string>>(o: T, k: K) {  var name: string = k; // OK}
load more v
75%

Code must use Number() to parse numeric values, and must check its return for NaN values explicitly, unless failing to parse is impossible from context.,Code that must parse using a radix must check that its input is a number before calling into parseInt;,Always use triple equals (===) and not equals (!==). The double equality operators cause error prone type coercions that are hard to understand and slower to implement for JavaScript Virtual Machines. See also the JavaScript equality table.,Code reviewers should be focused on improving the quality of the code, not enforcing arbitrary rules.

Tip: If you only need some of the elements from an array (or TypeScript tuple), you can insert extra commas in a destructuring statement to ignore in-between elements:

const [a, , b] = [1, 5, 10]; // a <- 1, b <- 10
load more v
40%

Presets enable Babel to parse types provided by Flow / TypeScript (and other dialects / languages), then strip them out when compiling down to JavaScript.,We highly encourage you to use a newer version of Node.js (LTS v8) since the previous versions are not maintained. See nodejs/LTS for more information.,@babel/preset-typescript,This just means Babel itself won't run on older versions of Node. It can still output code that runs on old Node versions.

Before it used to just be 2 imports:

import "core-js/shim"; // included < Stage 4 proposals
import "regenerator-runtime/runtime";

e.g.

// for core-js v2:
import "core-js/fn/array/flat-map";

// for core-js v3:
import "core-js/features/array/flat-map";

// core-js v2

// Stage 3
import "core-js/fn/string/trim-left";
import "core-js/fn/string/trim-right";
import "core-js/fn/string/match-all";
import "core-js/fn/array/flat-map";
import "core-js/fn/array/flatten"; // RENAMED
import "core-js/fn/global";

// Stage 1
import "core-js/fn/symbol/observable";
import "core-js/fn/promise/try";
import "core-js/fn/observable";

// Stage 1 Math Extensions
import "core-js/fn/math/clamp";
import "core-js/fn/math/deg-per-rad";
import "core-js/fn/math/degrees";
import "core-js/fn/math/fscale";
import "core-js/fn/math/iaddh";
import "core-js/fn/math/isubh";
import "core-js/fn/math/imulh";
import "core-js/fn/math/rad-per-deg";
import "core-js/fn/math/radians";
import "core-js/fn/math/scale";
import "core-js/fn/math/umulh";
import "core-js/fn/math/signbit";

// Stage 1 "of and from on collection constructors"
import "core-js/fn/map/of";
import "core-js/fn/set/of";
import "core-js/fn/weak-map/of";
import "core-js/fn/weak-set/of";
import "core-js/fn/map/from";
import "core-js/fn/set/from";
import "core-js/fn/weak-map/from";
import "core-js/fn/weak-set/from";

// Stage 0
import "core-js/fn/string/at";

// Nonstandard
import "core-js/fn/object/define-getter";
import "core-js/fn/object/define-setter";
import "core-js/fn/object/lookup-getter";
import "core-js/fn/object/lookup-setter";
// import "core-js/fn/map/to-json"; // Not available standalone
// import "core-js/fn/set/to-json"; // Not available standalone

import "core-js/fn/system/global";
import "core-js/fn/error/is-error";
import "core-js/fn/asap";

// Decorator metadata? Not sure of stage/proposal
import "core-js/fn/reflect/define-metadata";
import "core-js/fn/reflect/delete-metadata";
import "core-js/fn/reflect/get-metadata";
import "core-js/fn/reflect/get-metadata-keys";
import "core-js/fn/reflect/get-own-metadata";
import "core-js/fn/reflect/get-own-metadata-keys";
import "core-js/fn/reflect/has-metadata";
import "core-js/fn/reflect/has-own-metadata";
import "core-js/fn/reflect/metadata";

You can still use the shorthand version of a package name (remove the preset- or plugin-) in the config, but I'm choosing to use the whole package name for clarity (maybe we should just remove that, given it doesn't save that much typing anyway).

{
   -"presets": ["@babel/preset-react"],
   +"presets": ["@babel/react"], // this is equivalent
   -"plugins": ["@babel/transform-runtime"],
   +"plugins": ["@babel/plugin-transform-runtime"], // same
}

You can still use the shorthand way of specifying a preset or plugin. However because of the switch to scoped packages, you still have to specify the @babel/ just like if you had your own preset to add to the config.

module.exports = {
   presets: ["@babel/env"], // "@babel/preset-env"
   plugins: ["@babel/transform-arrow-functions"], // same as "@babel/plugin-transform-arrow-functions"
};

Babel 6's transformations for ES6 modules ran indiscriminately on whatever files it was told to process, never taking into account if the file actually had ES6 imports/exports in them. This had the effect of rewriting file-scoped references to this to be undefined and inserting "use strict" at the top of all CommonJS modules that were processed by Babel.

// input.js
this;
// output.js v6
"use strict"; // assumed strict modules
undefined; // changed this to undefined
// output.js v7
this;

This behavior has been restricted in Babel 7 so that for the transform-es2015-modules-commonjs transform, the file is only changed if it has ES6 imports or exports in the file. (Editor's note: This may change again if we land https://github.com/babel/babel/issues/6242, so we'll want to revisit this before publishing).

// input2.js
import "a";
// output.js v6 and v7
"use strict";
require("a");

Presets enable Babel to parse types provided by Flow / TypeScript (and other dialects / languages), then strip them out when compiling down to JavaScript.

{
   -"presets": ["@babel/preset-react"] +
   "presets": ["@babel/preset-react", "@babel/preset-flow"] // parse & remove flow types
   +
   "presets": ["@babel/preset-react", "@babel/preset-typescript"] // parse & remove typescript types
}

Note this does not apply to the CLI, where --presets es2015,es2016 will certainly still work.

{
   -"presets": "@babel/preset-env, @babel/preset-react" +
   "presets": ["@babel/preset-env", "@babel/preset-react"]
}

For presets and plugins values, this change means that the CLI will behave nicely in cases such as

babel--presets @babel / preset - env.. / file.js

Only Helpers

# install the runtime as a dependency
npm install @babel / runtime
# install the plugin as a devDependency
npm install @babel / plugin - transform - runtime--save - dev
{
   "plugins": ["@babel/plugin-transform-runtime"]
}

So if you need core-js support with transform-runtime, you would now pass the corejs option and use the @babel/runtime-corejs2 dependency instead of @babel/runtime.

# install the runtime as a dependency
npm install @babel / runtime - corejs2
# install the plugin as a devDependency
npm install @babel / plugin - transform - runtime--save - dev
{
   "plugins": [
      -["@babel/plugin-transform-runtime"],
      +["@babel/plugin-transform-runtime", {
         +"corejs": 2,
         +
      }],
   ]
}

A trailing comma cannot come after a RestElement in objects #290

var {
   -...y, // trailing comma is a SyntaxError
   +...y
} = {
   a: 1
};
// v7 default behavior: ["proposal-object-rest-spread"]
function _objectSpread(target) {
   ...
}

z = _objectSpread({
   x
}, y);
// Old v6 behavior: ["proposal-object-rest-spread", { "loose": true }]
function _extends(target) {
   ...
}

z = _extends({
   x
}, y);
// Substitute for Object.assign: ["proposal-object-rest-spread", { "loose": true, "useBuiltIns": true }]
z = Object.assign({
      x,
   },
   y
);

The default behavior is changed to what was previously "spec" by default

// input
class Bork {
   static a = "foo";
   y;
}
// v7 default behavior: ["@babel/plugin-proposal-class-properties"]
var Bork = function Bork() {
   Object.defineProperty(this, "y", {
      enumerable: true,
      writable: true,
      value: void 0,
   });
};

Object.defineProperty(Bork, "a", {
   enumerable: true,
   writable: true,
   value: "foo",
});
// old v6 behavior: ["@babel/plugin-proposal-class-properties", { "loose": true }]
var Bork = function Bork() {
   this.y = void 0;
};

Bork.a = "foo";

@babel/plugin-proposal-export-default-from

export v from "mod";

@babel/plugin-proposal-export-namespace-from

export * as ns from "mod";

It causes Babel 6 to throw Bad character escape sequence (5:6).

tag`\unicode and \u{55}`;

This has been fixed in Babel 7 and generates something like the following:

// default
function _taggedTemplateLiteral(strings, raw) {
   return Object.freeze(
      Object.defineProperties(strings, {
         raw: {
            value: Object.freeze(raw)
         }
      })
   );
}
var _templateObject = /*#__PURE__*/ _taggedTemplateLiteral(
   [void 0],
   ["\\unicode and \\u{55}"]
);
tag(_templateObject);
// loose mode
function _taggedTemplateLiteralLoose(strings, raw) {
   strings.raw = raw;
   return strings;
}
var _templateObject = /*#__PURE__*/ _taggedTemplateLiteralLoose(
   [void 0],
   ["\\unicode and \\u{55}"]
);
tag(_templateObject);

Default to previous "spec" mode for regular template literals

// input
`foo${bar}`;
// default v7 behavior: ["@babel/plugin-transform-template-literals"]
"foo".concat(bar);
// old v6 behavior: ["@babel/plugin-transform-template-literals", { "loose": true }]
"foo" + bar;

In anticipation of the new decorators proposal implementation, we've decided to make it the new default behavior. This means that to continue using the current decorators syntax/behavior, you must set the legacy option as true.

 {
    "plugins": [
       -"@babel/plugin-proposal-decorators" +
       ["@babel/plugin-proposal-decorators", {
          "legacy": true
       }]
    ]
 }

Newer proposals in flux will error by default and will require everyone to opt into a specific proposal while things are still < Stage 2. This is explained more in this post.

{
   "plugins": [
      -"@babel/plugin-proposal-pipeline-operator" +
      ["@babel/plugin-proposal-pipeline-operator", {
         "proposal": "minimal"
      }]
   ]
}
  class Point {
     constructor(x, y) {
           this.x = x;
           this.y = y;
        }

        -
        call constructor(x, y) {
           +static secondConstructor(x, y) {
              return new Point(x, y);
           }
        }

     let p1 = new Point(1, 2); -
     let p2 = Point(3, 4); +
     let p2 = Point.secondConstructor(3, 4);

We merged babel-plugin-transform-async-to-module-method into the regular async plugin by just making it an option.

{
   "plugins": [
      -["@babel/transform-async-to-module-method"] +
      ["@babel/transform-async-to-generator", {
         +"module": "bluebird",
         +"method": "coroutine" +
      }]
   ]
}

Install @babel/register as a new dependency:

npm install--save - dev @babel / register

Upgrading with Mocha:

-mocha--require babel - core / register +
   mocha--require @babel / register
load more v
22%

At the time when React was announced, Ember.js and Angular 1.x were the predominant choices as a framework. Both these imposed so many conventions on the code that porting an existing app was not convenient at all.,In React this means that:,first part second part,actions are triggered by the view

In this case, you add 2 script tags to the end of the body tag:

<html>
...

<body>
   ...
   <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.development.js" crossorigin></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js" crossorigin></script>
</body>

</html>
load more v
60%

This option tells Jest that all imported modules in your tests should be mocked automatically. All modules used in your tests will have a replacement implementation, keeping the API surface.,If the value is legacy, the old implementation will be used as implementation instead of one backed by @sinonjs/fake-timers.,For example, if you have tests in source files named with .t.js extension as following:,Use this configuration option to add custom reporters to Jest. A custom reporter is a class that implements onRunStart, onTestStart, onTestResult, onRunComplete methods that will be called when any of those events occurs.

Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:

package.json

Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:

jest.config.js

Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:

jest.config.ts

Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:

--config <path /to/file.js|ts|cjs|mjs|json>

Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:

package.json

Jest's configuration can be defined in the package.json file of your project, or through a jest.config.js, or jest.config.ts file or through the --config <path/to/file.js|ts|cjs|mjs|json> option. If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:

"jest"
load more v

Other "export-default" queries related to "“Export Default” in React Native Typescript causing Parsing Syntax Error"