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.
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);\
Introduce bebal file in the project root directory
.babel
Content:
{ presets:["es2015"] }
Install babel-cli
cnpm i babel-cli -g
Because you want to convert es6 to es5, you also need to install babel-preset-es2015
cnpm i babel-preset-es2015 --save-dev
Convert test1.js
babel src --out-dir dist
(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}
test3.js
import {bb} from 'test2.js' console.log(bb);
Convert babel src --out- dir dist
The page introduces test2.js test3.js under the dist file
Error report
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!