问题描述
写单个JS文件测试的时候,运行代码报“Cannot use import statement outside a module”
原因分析:
Module 的加载使用的是es6语法,需要改写/创建package.json文件,指明type类型为module。
解决方案:
1.把JS文件放在一个文件夹里,然后用VSCODE打开这个文件夹。
2.如果有package.json,在里面添加一行
“type”: "module"即可
{
"type": "module"
}
3.如果没有package.json,在终端执行npm init -y
npm init -y
会在文件夹里自动生成一个package.json文件,在里面添加一行"type": "module"即可。
{
"dependencies": {
"@humanwhocodes/env": "^2.2.2"
},
"type": "module", // 加这行就行,其它都是自动生成的。
"name": "test",
"version": "1.0.0",
"main": "test.js",
"devDependencies": {
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}