VS Code Notebook扩展中出现‘Cannot Use Import Outside of a Module’错误
解决VS Code Notebook单一扩展的"Cannot Use Import Outside of a Module"错误
核心问题
你的问题源于VS Code扩展的**主进程(Node.js环境)和渲染器(Webview浏览器环境)**对模块格式的要求冲突:主进程需要CommonJS格式,而渲染器需要ES模块格式,原模板的Webpack配置把两者都设为ES模块,导致主进程运行时报错。
正确解决方案
1. 修正Webpack配置(webpack.config.js)
- 恢复
experiments.outputModule配置,这是渲染器在Webview中运行的必要设置:
experiments: { outputModule: true, },
- 保持渲染器(client)的配置为ES模块:
makeConfig(argv, { entry: './src/client/index.ts', out: './out/client/index.js', target: 'web', library: 'module' }),
- 修改主进程(extension)的配置为Node.js兼容的CommonJS格式:
makeConfig(argv, { entry: './src/extension/extension.ts', out: './out/extension/extension.js', target: 'node', library: 'commonjs2' }),
2. 调整TypeScript配置
- 编辑
src/extension/tsconfig.json,确保主进程代码编译为CommonJS:
{ "compilerOptions": { "module": "CommonJS", "target": "ES2020", "outDir": "../../out/extension", "lib": ["ES2020"], "sourceMap": true, "rootDir": "." }, "include": ["**/*.ts"] }
- 保持
src/client/tsconfig.json的模块格式为ESNext,适配Webview环境:
{ "compilerOptions": { "module": "ESNext", "target": "ES2020", "outDir": "../../out/client", "lib": ["ES2020", "DOM"], "sourceMap": true, "rootDir": "." }, "include": ["**/*.ts"] }
3. 优化TextEncoder的导入
Node.js 16+已内置TextEncoder到全局对象,无需从util导入,直接使用即可:
// src/extension/extension.ts new globalThis.TextEncoder();
若需兼容旧版Node.js,可改用CommonJS语法导入:
const { TextEncoder } = require('util');
4. 重新编译调试
- 执行
npm run clean清除旧编译产物 - 执行
npm run compile重新构建 - 启动调试,此时主进程和渲染器的模块格式匹配各自环境,错误会消失。
错误原因分析
你之前将渲染器的library改为commonjs,导致Webview(浏览器环境)无法识别CommonJS的require语法,引发新错误。正确的做法是对主进程和渲染器采用差异化的模块配置,兼顾Node.js和浏览器的环境要求。
内容的提问来源于stack exchange,提问作者Kaksisve
相关产品推荐
相关产品推荐

