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

如何修改general-js-toolkit npm包以支持根路径导入语法?

修改npm包 general-js-toolkit 导入方式的具体方案

1. 重构项目入口结构

  • 在项目src目录下创建主入口文件index.js,将所有工具函数统一包装成对象导出:
// src/index.js
// 导入所有工具函数模块
import * as util from './util';

// 整合为统一的工具对象
const general_js = {
  ...util
};

// 同时支持默认导出和命名导出
export default general_js;
export { general_js };

2. 调整package.json配置

  • 更新入口字段,指向打包后的主文件(假设打包输出到dist/index.js):
{
  "name": "general-js-toolkit",
  "main": "dist/index.js",
  "module": "dist/index.js",
  // 保留原有其他配置
}
  • 若项目采用ES模块规范,添加type字段:
{
  "type": "module"
}

3. 调整打包工具配置(以Rollup为例)

确保打包输出支持多种模块规范,同时兼容浏览器全局变量:

// rollup.config.js
export default {
  input: 'src/index.js',
  output: [
    {
      file: 'dist/index.js',
      format: 'es',
      sourcemap: true
    },
    {
      file: 'dist/index.umd.js',
      format: 'umd',
      name: 'general_js', // 浏览器全局环境的变量名
      sourcemap: true
    }
  ],
  // 按需添加babel、压缩等插件配置
};
  • 若使用Webpack,需配置正确的库导出规则:
// webpack.config.js
module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'index.js',
    path: './dist',
    library: 'general_js',
    libraryTarget: 'umd',
    globalObject: 'this'
  },
  // 其他loader、插件配置
};

4. 重新打包并验证

  • 执行打包命令(如npm run build)生成新的发布文件。
  • 测试目标导入方式:
    • 默认导入调用:
      import general_js from 'general-js-toolkit';
      general_js.checkIsEmpty('example');
      
    • 命名导入调用:
      import { general_js } from 'general-js-toolkit';
      general_js.checkIsEmpty('example');
      

报错排查

如果仍出现Object(...) is not a function错误:

  • 检查打包后的文件是否正确导出了对象,而非单个函数。
  • 确认package.json的入口路径是否指向正确的打包文件。
  • 验证src/util中的函数是否通过export(而非export default)导出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:25:04