VSCode 使用教程-9.Node运行js出现 Cannot use import statement outside a module的问题

前言

js中导入公共模块,使用import的方式导入,用node运行js文件会出现Cannot use import statement outside a module的问题

问题描述

目录结构

└─src
    └─js
      └─ext.js
      └─main.js 
       
└─index.html

在ext.js 文件写一些公共方法

export const m = (function(){

    return {
        hello: function(){
            return 'hello ,,,,'
        },
        world: function(){
            return 'world !!!!!!!!'
        }
        
    }

})()

在main.js 文件中导入并调用方法

import {m} from './ext.js'
console.log(m.hello())

在html文件中,当js文件作为模块导入的时候,需在script标签声明type="module"类型

 <script type="module" src="./src/js/main.js"></script>

使用Open with live server方式打开html 是没有问题的。

如果我们想单独运行main.js 文件调试代码,使用node运行时,就会出现报错SyntaxError: Cannot use import statement outside a module

[Running] node "d:\code\web\src\js\main.js"
(node:6900) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
d:\code\web\src\js\main.js:1
import {m} from './ext.js'
^^^^^^

SyntaxError: Cannot use import statement outside a module

从警告中可以看到,需要在package.json中加一个配置"type": "module"

添加 package.json 文件

初始化项目,快速生成package.json

npm init -y

在终端输入上面命令,会在项目根目录创建一个package.json文件

在package.json中加一个配置"type": "module"

{
  "name": "web",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "module"
}

重新运行就不会报错了

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值