【问题标题】:Class (module) is not exported类(模块)未导出
【发布时间】:2020-11-17 14:49:53
【问题描述】:

模块:

import typeIs from './helpers/typeIs';

/**
 * @description Class of checking and throwing a custom exception.
 */
export default class Inspector {
// Some code
}

在package.json中指定了文件的路径:

{
// ....
"main": "dist/app.js",
// ...
}

我使用命令npm install ../ PACKAGE DIRECTORY / 在本地安装包。一切都已安装,但控制台返回 {}。可能是什么问题?

在缩小文件 (dist / app.js) 中返回一个空对象。如果您连接源 - 它可以工作。

.babelrc:

{
  "presets": ["@babel/preset-env"],

  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

package.json:

  "devDependencies": {
    "@babel/core": "^7.10.5",
    "@babel/preset-env": "^7.10.4",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^26.1.0",
    "babel-loader": "^8.1.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "clean-webpack-plugin": "^3.0.0",
    "cross-env": "^7.0.2",
    "eslint": "^7.5.0",
    "eslint-config-google": "^0.14.0",
    "eslint-loader": "^4.0.2",
    "jest": "^26.1.0",
    "webpack": "^4.44.0",
    "webpack-cli": "^3.3.12"
  },
  "browserslist": "> 0.25%, not dead",
  "dependencies": {
    "@babel/polyfill": "^7.10.4"
  }

UPD 我检查一下

const Inspector = require('inspector-with-exceptions');

console.dir(Inspector);

【问题讨论】:

  • "控制台返回{}" - 什么时候做什么?
  • 您的代码中实际上包含exports = {…};、exports['…'] = …; 和module.exports = …; 中的哪一个?第一个不起作用。
  • 为什么不写 ES6 模块语法时使用transform-es2015-modules-commonjs?
  • 哦,这是一个不同的问题 :-) 试试 require('inspector-with-exceptions').default,或者也使用 ES6 模块语法进行导入:import Inspector from 'inspector-with-exceptions';。

标签: javascript node.js npm webpack


【解决方案1】:

导入模块的常见错误之一是忘记将它们设为相对。 require('inspector-with-exceptions') 和 require('./inspector-with-exceptions') 之间的区别在于,第一个查看您的 node_modules,第二个查看您的文件系统。我认为您的代码中的问题是。

编辑:自上周以来,我遇到了很多这个问题。幸运的是我找到了解决它的方法。所以处理这个问题最简单的方法是在 webpack.config.js 中设置你的输出属性,如下所示:

//Rest of you webpack file
output: {
  path: path.resolve(__dirname, 'dist'),
  filename: <project-name>.js,
  libraryTarget: 'commonjs2',
  libraryExport: 'default',
  library: <ProjectName>
}

使用我在 中显示的情况。希望这会有所帮助。

【讨论】:

猜你喜欢
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多