Declaration or statement expected javascript ошибка

I am using Typescript 1.7 and React 0.14 with the new ES6 systax and I’m having the following destructuring assignment, as explained here as well.

let x0, x1, y0, y1;
if(this.props.viewport) {
    {x0, x1, y0, y1} = this.props.viewport;
}

However, I’m getting the Declaration or statement expected error. What am I doing wrong?

Thanks

S M's user avatar

S M

3,1535 gold badges30 silver badges59 bronze badges

asked Feb 23, 2016 at 11:26

XeniaSis's user avatar

4

So, I found the problem. Had to wrap the whole line in parenthesis. So the following is correct.

let x0, x1, y0, y1;
if(this.props.viewport) {
    ({x0, x1, y0, y1} = this.props.viewport);
}

answered Feb 23, 2016 at 11:32

XeniaSis's user avatar

XeniaSisXeniaSis

2,1925 gold badges24 silver badges39 bronze badges

4

I had this problem because I was trying to use case as a variable name e.g. var case = .... Now I know this error was because case is already used by JavaScript’s Switch Statement.

answered Jul 26, 2018 at 20:34

Worm's user avatar

WormWorm

1,3332 gold badges12 silver badges28 bronze badges

1

If you create the variables and assign to them the values in the same line, you can do it like so:

let person = {name: "Alex", age: 23, favoriteColor: "orange"}

let {name, age} = person

document.write(name + " is " + age + " years old")

In case you first declare the variables and then on another line you assign the values, the approach is different, it needs the parenthesis to be parsed correctly. Like so:

let person = {name: "Alex", age: 23, favoriteColor: "orange"}

let name, age;

({name, age} = person)

document.write(name + " is " + age + " years old")

In case you want to assign values to a property from an object or a getter inside a class, it is a little bit tricky, it would look like so:

({name: this.name, age: this.age} = this.person) 

answered Mar 14 at 8:46

Gass's user avatar

GassGass

7,5543 gold badges37 silver badges41 bronze badges

I am using Typescript 1.7 and React 0.14 with the new ES6 systax and I’m having the following destructuring assignment, as explained here as well.

let x0, x1, y0, y1;
if(this.props.viewport) {
    {x0, x1, y0, y1} = this.props.viewport;
}

However, I’m getting the Declaration or statement expected error. What am I doing wrong?

Thanks

S M's user avatar

S M

3,1535 gold badges30 silver badges59 bronze badges

asked Feb 23, 2016 at 11:26

XeniaSis's user avatar

4

So, I found the problem. Had to wrap the whole line in parenthesis. So the following is correct.

let x0, x1, y0, y1;
if(this.props.viewport) {
    ({x0, x1, y0, y1} = this.props.viewport);
}

answered Feb 23, 2016 at 11:32

XeniaSis's user avatar

XeniaSisXeniaSis

2,1925 gold badges24 silver badges39 bronze badges

4

I had this problem because I was trying to use case as a variable name e.g. var case = .... Now I know this error was because case is already used by JavaScript’s Switch Statement.

answered Jul 26, 2018 at 20:34

Worm's user avatar

WormWorm

1,3332 gold badges12 silver badges28 bronze badges

1

If you create the variables and assign to them the values in the same line, you can do it like so:

let person = {name: "Alex", age: 23, favoriteColor: "orange"}

let {name, age} = person

document.write(name + " is " + age + " years old")

In case you first declare the variables and then on another line you assign the values, the approach is different, it needs the parenthesis to be parsed correctly. Like so:

let person = {name: "Alex", age: 23, favoriteColor: "orange"}

let name, age;

({name, age} = person)

document.write(name + " is " + age + " years old")

In case you want to assign values to a property from an object or a getter inside a class, it is a little bit tricky, it would look like so:

({name: this.name, age: this.age} = this.person) 

answered Mar 14 at 8:46

Gass's user avatar

GassGass

7,5543 gold badges37 silver badges41 bronze badges

  1. HowTo
  2. TypeScript Howtos
  3. Declaration or Statement Expected Error …

Muhammad Ibrahim Alvi
Apr 04, 2022

Declaration or Statement Expected Error in TypeScript

This tutorial explains the Declaration or statement expected error in JavaScript or TypeScript and why the compiler throws this error. All the major reasons for this error will be discussed, and how it can be avoided among the developer’s community.

Declaration or statement expected Error in JavaScript or TypeScript

The Declaration or statement expected error in JavaScript or TypeScript occurs when we have a syntax error in the code.

For instance, consider the destructuring of an object in the file with the wrong syntax, exporting a module in the file with the wrong name, or having a missing or inconsistent bracket.

Consider the following example of a code where a different Declaration or statement expected occurs due to the syntax error inside the code.

let oneData: number;

const obj = {
  val: 1,
};

// 1. ⛔️ Parsing error: Declaration or statement expected.
{ oneData } = obj; // 👈️ this must be wrapped in parenthesis

const sumObj = (a: number, b: number) => a + b;

// 2. ⛔️ Error: Parsing error: Declaration or statement expected.eslint
export sumObj // 👈️ should be export {sum}

// 3. Make sure you're not using reserved words
const caseVal = 'hello world' // 👈️ case is reserved word

The above code produces the following errors, which are written below.

//output or errors
Variable 'one' is used before being assigned.

Declaration or statement expected. This '=' follows a block of statements, so if you intend to write a destructuring assignment, you might need to wrap the whole assignment in parentheses.

Declaration or statement expected.

'case' is not allowed as a variable declaration name.

Variable declaration expected.

Variable declaration expected.

Declaration or statement expected error

Consider the following code, compiled correctly with no Declaration or statement expected errors.

let val: number;

const obj = {
  val: 1,
};

// ✅ OK
({ val } = obj); // 👈️ this must be wrapped in parenthesis

console.log(val); // 👉️ 1

The above code produces the following output.

Declaration or statement expected error - solution

Declaration or statement expected error also arises sometimes when exporting something that has been declared previously. Whenever this needed to be done, wrap the export in curly braces.

const objSum = (a: number, b: number) => a + b;

// ✅ OK
export { objSum };

Muhammad Ibrahim Alvi avatar
Muhammad Ibrahim Alvi avatar

Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.

LinkedIn

Всем привет.Стараюсь собрать проект с помощью babel,webpack.Проект на typescript,react,scss.Получаю ошибку:

ERROR in src/components/App/app.scss:1:0
[unknown]: Parsing error: Declaration or statement expected.
  > 1 | .title{
    2 |     color:red;
    3 |     text-align: center;
    4 | }

ERROR in src/components/App/app.scss.d.ts:3:11
@typescript-eslint/no-empty-interface: An empty interface is equivalent to `{}`.
    1 | // This file is automatically generated.
    2 | // Please do not change this file!
  > 3 | interface CssExports {
      |           ^^^^^^^^^^
    4 | 
    5 | }
    6 | export const cssExports: CssExports;

webpack 5.11.1 compiled with 3 errors in 3556 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! chat@1.0.0 build-dev: `webpack --env.mode=development`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the chat@1.0.0 build-dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/nikita/.npm/_logs/2020-12-31T16_13_00_338Z-debug.log

.babelrc

{
  "presets": [
    [
      "@babel/env",
      {
        "corejs": 3,
        "useBuiltIns": "usage",
        "debug": true,
        "modules": false
      }
    ],
    "@babel/react",
    "@babel/typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ]
  ]
}

webpack.config.js

const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')


module.exports = (env = {}) => {

  const { mode = 'development' } = env;

  const isProd = mode === 'production';
  const isDev = mode === 'development';

  const getStyleLoaders = () => {
    return [
      isProd ? MiniCssExtractPlugin.loader : 'style-loader'
    ]
  }

  const getPlugins = () => {
    const plugins = [
      new HtmlWebpackPlugin({
        title: 'Chat',
        buildTime: new Date().toISOString(),
        template: 'public/index.html'
      }),
      new ForkTsCheckerWebpackPlugin({
        async:false,
        eslint:{
          files: "./src/**/*"
        }
      })
    ];
    if (isProd) {
      plugins.push(new MiniCssExtractPlugin({
        filename: 'main-[hash:8].css'
      }))
    }

    return plugins
  }

  return {
    mode: isProd ? 'production' : isDev && 'development',

    resolve: {
      extensions: [".tsx", ".ts", ".js"],
    },

    output:{
      filename: isProd ? 'main-[hash:8].js' : undefined
    },

    module: {
      rules: [
        {
          test:/\.(ts|js)x?/,
          exclude:/node_modules/,
          use:{
            loader:"babel-loader",
            options:{
              presets:[
                "@babel/preset-env",
                "@babel/preset-react",
                "@babel/preset-typescript"
              ]
            }
          }
        },
        // Loading images
        {
          test: /\.(png|jpg|gif|ico|jpeg)$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                outputPath: 'images', 
                name: '[name]-[sha1:hash:7].[ext]'
              }
            }
          ]
        },
        // Loading fonts
        {
          test: /\.(ttf|otf|eot|woff|woff2)$/, 
          use: [
            {
              loader: 'file-loader',
              options: {
                outputPath: 'images',   
                name: '[name]-[sha1:hash:7].[ext]'
              }
            }
          ]
        },
        {
          test: /\.(sa|sc|c)ss$/, 
          use: [
            ...getStyleLoaders(),
            "css-modules-typescript-loader",
            'css-loader',
            "postcss-loader",
            "sass-loader"
          ]
        }
      ]
    },


    plugins: getPlugins(),


    devServer: {
      open: true, 
    }
  }
}

tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "allowJs": true,
    "jsx": "react",
    "outDir": "./dist",
    "rootDir": "./",
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": "./src",
    "typeRoots": ["node_modules/@types", "src/typings"],
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

eslintrc.json

{
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
      "ecmaVersion": 2018,
      "sourceType": "module"
    },
    "plugins": [
      "@typescript-eslint",
      "react-hooks"
    ],
    "extends": [
      "plugin:react/recommended",
      "plugin:@typescript-eslint/recommended"
    ],
    "rules": {
      "react-hooks/rules-of-hooks": "error",
      "react-hooks/exhaustive-deps": "warn",
      "react/prop-types": "off"
    },
    "settings": {
      "react": {
        "pragma": "React",
        "version": "detect"
      }
    }
  }

5fedf85561728671314473.png

SitePoint Forums | Web Development & Design Community

Loading

Понравилась статья? Поделить с друзьями:
  • Deceit код ошибки 30005
  • Debugmsg dll ошибка
  • Debian проверка диска на ошибки при загрузке
  • Debug error c abort has been called ошибка
  • Debootstrap код ошибки 1