Tag Archives: js

Solve the problem of JS using JSX syntax to report errors in vite react project


During the vite test of stock items, it is found that many stock (old) items directly write JSX syntax in JS, and a lot of problems will be thrown when vite is used to start failed to parse source .

It’s not too much trouble to run a script to modify the file type in batch. This is a solution.

In order to get to the bottom of the matter and access vite for the lowest cost of stock projects, try to avoid modifying the business code. We have to find another way to solve it.

The screenshot of error reporting is as follows

Recurrence problem

Initialize demo project

# npm 6.x
npm init [email protected] my-react-app --template react-ts

# npm 7+, extra double-dash is needed:
npm init [email protected] my-react-app -- --template react-ts

# yarn
yarn create vite my-react-app --template react-ts

The contents are as follows

├── index.html
├── package.json
├── src
|  ├── App.css
|  ├── App.tsx
|  ├── favicon.svg
|  ├── index.css
|  ├── logo.svg
|  ├── main.tsx
|  └── vite-env.d.ts
├── tsconfig.json
└── vite.config.ts


npm run dev

The page is normal. Next, modify app. TSX to app. JS

You will get the above error report


    Vite will do the dependent pre build at startup

    pre built , runtime only performs syntax conversion between JSX and TSX by default. Will not do JSX syntax conversion for JS.


    Modify the configuration that depends on the pre build

    Use the Babel plug-in @ Babel/plugin transform react JSX , and let vite convert JS files at runtime

Add a little configuration to the configuration file as described in the document

export default defineConfig({
  optimizeDeps: {
    entries: [],

By reading the documentation of @ vite/plugin react , we found that it supports incoming Babel plug-ins

npm i @babel/plugin-transform-react-jsx

Add plug-in

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react({
      babel: {
        plugins: ['@babel/plugin-transform-react-jsx'],

Start the verification again and an error is found

The reason is that react is not introduced into app.js. Let’s introduce it

import React,{ useState } from 'react'

be accomplished


Two treatment schemes

    File suffix JS = & gt; jsx

    Modify the dependency pre build configuration and add Babel plug-in @ Babel/plugin transform react JSX

The second method will affect the startup speed of the project to a certain extent. Readers can pick the scheme according to the actual project situation


Welcome to share/exchange some problems and lessons learned when accessing vite in the development process in the comment area

Source address

JS declares two variables with the same variable name

When writing, you should probably not write the same variable name, that is, the local variable and the global variable may have the same name

However, when both are variables in the same region, such as all global variables

other languages probably report errors, but JS is too tolerant. It’s a little difficult to report errors

        var t={
        var t="ss";

Now the second is equivalent to


How does eclipse ignore JS files with errors

The first step is to locate the error, select window – show view – other in the menu, and select problems


Step 2: click the item with Red Cross. In the problems view, you can see what the error is and the JS error in which folder


Step 3: after locating the error, right-click the item with the Red Cross, select properties, and the Properties box pops up

Step 4: in the pop-up menu, select include path under JavaScript directory, select excluded under source on the right, and then click Add Folder


Step 5: in the pop-up box, under exclusion patterns, click the Add button on the right to add the path to be ignored


Step 6: click add, select browse in the pop-up box, and select the file to be ignored under the project




Step 6: click OK and return to the project directory. You will see that the projects that reported the red cross just now have returned to normal

Welcome to my personal blog – Fu Bohan’s personal blog   vast waves


Error in JS function referencing public page [How to Solve]

For the website, there are a large number of sharing modules between many pages, such as page header, footer and user bar. Many times, in order to be convenient and easy, we write functions in public modules and call them in other pages. However, when we reference public JS functions, some can be referenced, but some report errors this is because of the problem of JS loading, that is, when the current page is loaded, but some public pages reference public JS before loading, it will report that this function is not found


The results are as follows:

JS referencing public footer

The results are as follows:

from the above two examples, we can know that the loading order of JS is from top to bottom. The header is loaded first – the current page – the footer. Finally, if all the current pages reference the footer that has not been loaded, JS will report “F”_public is not defined”


The solution is as follows:

$(document).ready(function () {

when the DOM (document object model) has been loaded and the page (including image) has been completely rendered, the ready event will occur; This function is not called until the footer is loaded

page execution sequence in JS

1: Use $(function) {} of jQuery

2: Use $(document). Ready (function() {}) of jQuery; There is no essential difference between the first two. The first is the abbreviation of the second. The second is to execute the method after the document is loaded

3: Use $(window). Load (function() {}) of jQuery

4: Use window. Onload = function() {} the third and fourth methods wait until the whole window is loaded to execute the method body. There is no difference between the two, except that one uses DOM objects and the other uses jQuery objects

5: Statically bind the onload event on the tag, & lt; body onload=”aaa()”> When the body is loaded, the AAA () method is executed


So, what is the implementation order of these five methods

Through the following code verification, it is found that:

Use $(function) {} of 1: jQuery and $(document). Ready (function() {}) of 2: jQuery; No matter where the position is placed, the other three methods always take precedence (the reason is that these two methods are executed after the document is loaded, and the last three methods are executed after the whole window page is loaded). The execution order between the two is who is at the top and who takes precedence

Use $(window). Load (function() {}) of 3: jQuery

4: window. Onload = function bbb() {} always takes precedence over & lt; body onload=”aaa()”> Execution. Their execution order is also based on who is at the top and who is first

Use 5: & lt; body onload=”aaa()”> Always last

<script type='text/javascript'>

  window.onload = function(){
    alert("Page loading completed====》onload");

    alert("jquery===》window load" );

  $(document).ready(function () {
    alert("jquery====》document ready");

    alert("jquery====》document onload");

  function aaa(){
    alert("Static labels====》onload");


<body onload="aaa()">



On the error of cannot read property ‘xxx’ of null in JS


When debugging the page, there was such an error. The search found that this error occurred before the page was loaded when JS was loaded. The solution is very simple. Put this section of JS at the bottom of the page, and then load this section of JS when the page is loaded. Make a brief note

Success comes from diligence

[How to Solve] Cannot set property ‘onclick’ of null

<!DOCTYPE html>
        <meta charset="utf-8">
            //Get this element from the document based on the value of the id attribute
            var btnObj=document.getElementById("btn");
            // for the current button element (object), register the click event, add the event handler (anonymous function)
                //response to do something
        <input type="button" value="Display effect" id="btn" />    

After the above code is executed, the

To make changes, you need to put the JS file at the bottom of and load it

<!DOCTYPE html>
        <meta charset="utf-8">
        <input type="button" value="show effect" id="btn" />    
            //get this element from the document based on the value of the id attribute
            var btnObj=document.getElementById("btn");
            // for the current button element (object), register the click event, add the event handler (anonymous function)
                //response to do something

The code executes normally

Reason: when the JS file is placed in the head, if the onclick or OnMouseOver event is bound, a similar error will appear as shown in the figure above. The reason is that the order of loading the HTML document you write is from top to bottom, and the JS is executed only after the button node is loaded. Therefore, when the browser parses from top to bottom, the button node bound to onclick cannot be found, so an error is reported

The solution: first, load the JS file at the bottom; Second, use window. Onload = function () {} to wrap JS content

Js Error: SyntaxError: identifier starts immediately after numeric literal

SyntaxError: identifier starts immediately after numeric literal

Today I wrote a onclick() method, there is such a variable 4028b88161c881ff0161c88b80dc0002

I need to pass the value of this variable into the method, but it never works:

I found that directly var aa =4028b88161c881ff0161c88b80dc0002 ;js is holding the error

The solution is as follows:


var str = “509edbe9-2914-431f-9128-97d368b7da0b”;

//The wrong way to write it
var html = ‘<button class=”button” id=”ensure” onclick=”test(str)”>OK</button>’;// Passing a string as an argument to a function reports an error directly

//The correct way to write it

var html = ‘<button class=”button” id=”ensure” onclick=”test(\”+str+’\’)”>OK</button>’;//execute correctly, note that the first \ is followed by two single quotes


function test(id){
<div id=”dd”></div>

ToFixed, toexponential, toprecision in JS

ToFixed (): converts a number to a string according to the specified number of digits after the decimal point. It does not use exponential counting

Toexponential(): converts a number to an exponential string according to the number of digits specified after the decimal point. There is only one digit before the decimal point, and the number of digits after the decimal point is specified by parameters

Toprecision(): converts a number to a string based on the number of significant digits. If the number of significant digits is less than the integer part of the number, it is expressed as an exponential string

The above three methods all follow the principle of “rounding off” or filling 0

Here are some examples:

var num = 1234567.8999;
console.log("num.toFixed(0):" + num.toFixed(0));
console.log("num.toFixed(2)" + num.toFixed(2));
console.log("num.toFixed(5)" + num.toFixed(5));
console.log("num.toFixed(12)" + num.toFixed(12));

console.log("num.toExponential(3):" + num.toExponential(3));
console.log("num.toExponential(0):" + num.toExponential(0));

console.log("num.toPrecision(1):" + num.toPrecision(1));
console.log("num.toPrecision(5)" + num.toPrecision(5));
console.log("num.toPrecision(12)" + num.toPrecision(12));

Corresponding to the following output:

JS Unexpected syntax error: unexpected string

JS error, finally found that the $(function () {}) part () is incomplete

                        alert("The system is busy, please try again later!");

After summarizing the previous errors, it is found that most of the errors are incomplete symbols, such as missing a bracket or a quotation mark