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"
}

重新运行就不会报错了

posted @   上海-悠悠  阅读(1704)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-09-16 python测试开发django-133.Bootstrap 容器 container和 container-fluid
2021-09-16 python测试开发django-132.Bootstrap Table设置表头样式(theadClasses)
2021-09-16 python测试开发django-131.jQuery中$.ajax()方法POST提交contentType:"application/json"类型数据
2021-09-16 python测试开发django-130.jQuery中$.ajax()方法发GET/POST/DELETE请求
2021-09-16 python测试开发django-129.jQuery中$.get()和$.post()提交方法学习
2020-09-16 pytest文档58-随机执行测试用例(pytest-random-order)
点击右上角即可分享
微信分享提示