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

Webpack 5打包库无法被本地包导入,导出报错求助

问题

用Webpack 5打包库后,在另一个项目中导入时出现两类报错:

  • 默认导入时:SyntaxError: The requested module 'test-module' does not provide an export named 'default'
  • 命名导入时:SyntaxError: The requested module 'test-module' does not provide an export named 'log'

文件结构如下:

|- test/
|  |- src/
|  |  |- index.js
|  |- package.json
|  |- webpack.config.js
|- src/
|  |- index.js
|  |- package.json

其中test/存放库的源码与打包产物,src/是导入该库的测试项目。

库文件详情

test/package.json:

{
  "name": "test-module",
  "type": "module",
  "module": "lib/bundle.js",
  "version": "0.0.1",
  "description": "",
  "main": "lib/bundle.js",
  "author": "",
  "license": "ISC",
  "scripts": {
    "build": "webpack --config webpack.config.js"
  },
  "devDependencies": {
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"
  }
}

test/webpack.config.js:

import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default {
  mode: 'production',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'lib'),
    filename: 'bundle.js',
    library: {
      name: 'log',
      type: 'umd',
      umdNamedDefine: true,
      export: 'default'
    },
    clean: true
  }
};

test/src/index.js:

export function log(param) {
  console.log(param)
}

export default log;

测试项目文件详情

src/package.json:

{
  "name": "test-src",
  "type": "module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "test-module": "file:../test"
  }
}

src/index.js:

import log from 'test-module'
log('hi')

运行npm start时触发默认导入报错。


解决方法

1. 调整Webpack配置,输出ES模块格式

当前配置使用umd类型输出,与库的type: module属性不兼容,导致Node解析ES模块时无法识别导出内容。修改test/webpack.config.js:

import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default {
  mode: 'production',
  entry: './src/index.js',
  experiments: {
    outputModule: true // 启用ES模块输出实验特性
  },
  output: {
    path: path.resolve(__dirname, 'lib'),
    filename: 'bundle.js',
    library: {
      type: 'module' // 指定输出为ES模块
    },
    clean: true
  }
};

移除原配置中name、umdNamedDefine、export等UMD相关字段,让Webpack输出标准ES模块。

2. 重新打包并验证

进入test目录执行npm run build重新打包,回到src目录运行npm start,此时默认导入import log from 'test-module'可正常调用。

若需要使用命名导入import { log } from 'test-module',由于源码中已包含命名导出,修改配置后该方式也能正常工作。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:24:20