Home > Web Front-end > JS Tutorial > How to solve the es6 import error problem

How to solve the es6 import error problem

藏色散人
Release: 2023-01-07 11:47:13
Original
3460 people have browsed it

Solution to es6 import error: 1. Use bebal to convert es6 to es5; 2. Pack through webpack, merge all dependencies into one file, and then use babel to convert.

How to solve the es6 import error problem

The operating environment of this article: Windows 7 system, ECMAScript version 6, Dell G3 computer.

How to solve the es6 import error problem?

Most browsers now do not support ES6, so when using es6, you need to use bebal to convert es6 to es5.

Project directory:

  • demo1: Conversion of a single js file

test1.js under the src file

const aa="this is test1";
console.log("this is from test1",aa);\
Copy after login

Introduce bebal file in the project root directory

.babel
Copy after login

Content:

{
  presets:["es2015"]
}
Copy after login

Install babel-cli

cnpm i babel-cli -g
Copy after login

Because you want to convert es6 to es5, you also need to install babel-preset-es2015

cnpm i babel-preset-es2015 --save-dev
Copy after login

Convert test1.js

babel src --out-dir dist
Copy after login

(Convert the js file in the src directory to es5 and put it in the dist file)

The page introduces test1.js under dist and runs without error

  • demo2: Multiple file projects are introduced and converted

src file:

test2.js

const bb="this is bb";
export {bb}
Copy after login

test3.js

import {bb} from 'test2.js'
console.log(bb);
Copy after login

Convert babel src --out- dir dist

The page introduces test2.js test3.js under the dist file

Error report

How to solve the es6 import error problem

Because we compile ES6 through node; In es5, the node module is based on CommonJS specifications, and current browsers and node do not support most of ES6

Solution

You can use webpack Pack it, merge all the dependencies into one file, use babel to convert it, and then introduce it into the html file

Recommended study: "JavaScript Basics Tutorial

The above is the detailed content of How to solve the es6 import error problem. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template