You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Webpack开发VSCode扩展时出现ReferenceError: require未定义

问题:VSCode扩展开发中Webpack打包后出现ReferenceError: require is not defined

背景

  • 具备Golang、Python开发基础,刚接触JavaScript、TypeScript及Node.js
  • 正在使用Webpack+TypeScript开发VSCode扩展,期望实现TS与JS代码混用

项目结构

├── CHANGELOG.md
├── README.md
├── dist
│   ├── extension.js
│   └── extension.js.map
├── node_modules  [244 entries exceeds filelimit, not opening dir]
├── out
│   ├── auth
│   │   ├── auth.js
│   │   └── auth.js.map
│   ├── extension.js
│   ├── extension.js.map
│   ├── media
│   │   ├── main.js
│   │   └── main.js.map
│   ├── providers
│   │   ├── MyViewProvider.js
│   │   └── MyViewProvider.js.map
│   └── test
│       ├── extension.test.js
│       └── extension.test.js.map
├── package-lock.json
├── package.json
├── src
│   ├── auth
│   │   └── auth.ts
│   ├── extension.ts
│   ├── media
│   │   ├── main.css
│   │   ├── main.ts
│   │   ├── reset.css
│   │   └── vscode.css
│   ├── providers
│   │   └── MyViewProvider.ts
│   └── test
│       └── extension.test.ts
├── tsconfig.json
├── vsc-extension-quickstart.md
└── webpack.config.js

tsconfig.json配置

{
    "compilerOptions": {
        "module": "Node16",
        "target": "ES2022",
        "lib": [
            "DOM",
            "ES2022"
        ],
        "sourceMap": true,
        "rootDir": "src",
        "strict": true   /* enable all strict type-checking options */
        /* Additional Checks */
        // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
        // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
        // "noUnusedParameters": true,  /* Report errors on unused parameters. */
    }
}

webpack.config.js配置

//@ts-check

'use strict';

const path = require('path');

//@ts-check
/** @typedef {import('webpack').Configuration} WebpackConfig **/

/** @type WebpackConfig */
const extensionConfig = {
  target: 'web', // VS Code extensions run in a Node.js-context 📖 -> https://webpack.js.org/configuration/node/
    mode: 'development', // this leaves the source code as close as possible to the original (when packaging we set this to 'production')

  entry: './src/extension.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/
  output: {
    // the bundle is stored in the 'dist' folder (check package.json), 📖 -> https://webpack.js.org/configuration/output/
    path: path.resolve(__dirname, 'dist'),
    filename: 'extension.js',
    libraryTarget: 'commonjs2'
  },
  externals: {
    vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, 📖 -> https://webpack.js.org/configuration/externals/
    // modules added here also need to be added in the .vscodeignore file
  },
  resolve: {
    // support reading TypeScript and JavaScript files, 📖 -> https://github.com/TypeStrong/ts-loader
    extensions: ['.ts', '.js']
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader'
          }
        ]
      }
    ]
  },
  devtool: 'nosources-source-map',
  infrastructureLogging: {
    level: "log", // enables logging required for problem matchers
  },
};
module.exports = [ extensionConfig ];

当前问题

  • 在extension.ts中执行import * as vscode from 'vscode';,npm run compile编译正常
  • 但在VSCode开发宿主中运行扩展时,开发者日志抛出错误:ReferenceError: require is not defined

最终目标

  • 让extension.js导入MyViewProvider.ts中的提供者类(该类包含Webview所需HTML等内容)
  • 在Webview的HTML中加载指向src/auth/auth.ts的脚本

解决思路建议

1. 修正Webpack的target配置

VSCode扩展运行在Node.js环境,当前Webpack配置中target: 'web'是错误的,会打包出浏览器环境的代码,缺失Node.js的require模块加载逻辑。修改为:

target: 'node', // 替换原有的'web'配置

2. 确保TS与Webpack模块配置对齐

tsconfig.json中设置了module: 'Node16',修改Webpack target为node后,ts-loader会正确处理Node.js模块规范,和TS的配置兼容,解决require未定义的核心问题。

3. 验证externals配置

当前vscode: 'commonjs vscode'的externals配置是正确的,它告诉Webpack不要打包vscode模块,而是在运行时通过Node.js的require加载,修正target后该配置即可正常工作。

4. TS/JS混用的实现

Webpack的resolve配置已经包含了extensions: ['.ts', '.js'],只要JS文件遵循Node.js模块规范(CommonJS或ES模块),就能直接在TS代码中导入使用,无需额外配置。

5. Webview加载auth.ts的处理

Webview运行在浏览器环境,无法直接加载Node.js模块,需要单独打包auth.ts:

  • 在webpack.config.js中新增一个针对web target的配置,入口设为src/auth/auth.ts,输出到dist/media目录
  • 在Webview的HTML中通过<script>标签引入打包后的auth.js文件,而非直接引用src下的ts源文件

内容的提问来源于stack exchange,提问作者Anthony Quinn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 07:20:24