简体   繁体   English

webpack 导入的模块不是构造函数

[英]webpack imported module is not a constructor

I created a small JS module which I intend to make an npm package, but for now is just on GitHub. This module is written in ES6 and SCSS, and is thus relying on webpack and babel for transpilation.我创建了一个小的 JS 模块,我打算制作一个 npm package,但现在只是在 GitHub 上。这个模块是用 ES6 和 SCSS 编写的,因此依赖 webpack 和 babel 进行编译。

To test it, I created a separate project with a similar setup (webpack and babel).为了测试它,我创建了一个具有类似设置(webpack 和 babel)的单独项目。 After npm installing my module, when trying to import it into my index.js, I get the following error in Chrome Developer Tools: (with x being my module's name) npm 安装我的模块后,尝试将其导入我的 index.js 时,我在 Chrome 开发人员工具中收到以下错误:(x 是我的模块名称)

index.js:11 Uncaught TypeError: x__WEBPACK_IMPORTED_MODULE_1___default.a is not a constructor
    at eval (index.js:11)
    at Object../src/index.js (main.js:368)
    at __webpack_require__ (main.js:20)
    at eval (webpack:///multi_(:8081/webpack)-dev-server/client?:2:18)
    at Object.0 (main.js:390)
    at __webpack_require__ (main.js:20)
    at main.js:69
    at main.js:72

I've looked through countless answers and tried countless solutions, to no avail.我翻阅了无数答案并尝试了无数解决方案,但无济于事。 My module's setup is as follows.我的模块设置如下。

.babelrc .babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["ie >= 11"]
      }
    }]
  ],
  "plugins": [
    "transform-es2015-modules-commonjs",
    "transform-class-properties"
  ]
}

webpack.common.js webpack.common.js

const path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const cleanWebpackPlugin = require('clean-webpack-plugin')

const baseSCSS = new ExtractTextPlugin('main/_base.css')
const themeSCSS = new ExtractTextPlugin('main/_theme.css')

module.exports = {
  entry: {
    example: [
      path.join(__dirname, 'src', 'example', 'index.js')
    ],
    main: [
      'idempotent-babel-polyfill',
      path.join(__dirname, 'src', 'index.js')
    ]
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: path.join('[name]', 'index.js')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        }
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract(
          {
            fallback: 'style-loader',
            use: ['css-loader', 'sass-loader']
          }
        )
      },
      {
        test: /\_base-scss$/,
        use: baseSCSS.extract(
          {
            fallback: 'style-loader',
            use: ['css-loader', 'sass-loader']
          }
        )
      },
      {
        test: /\_theme-scss$/,
        use: themeSCSS.extract(
          {
            fallback: 'style-loader',
            use: ['css-loader', 'sass-loader']
          }
        )
      }
    ]
  },
  plugins: [
    new cleanWebpackPlugin('dist', {}),
    new ExtractTextPlugin({ filename: path.join('example', 'style.css') }),
    baseSCSS,
    themeSCSS,
    new HtmlWebpackPlugin({
      inject: false,
      hash: true,
      template: path.join(__dirname, 'src', 'example', 'index.html'),
      filename: path.join('example', 'index.html')
    })
  ]
}

webpack.prod.js webpack.prod.js

const merge = require('webpack-merge')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const webpack = require('webpack')
const common = require('./webpack.common.js')

module.exports = merge(common, {
  plugins: [
    new UglifyJSPlugin({
      sourceMap: true
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
  ],
  mode: 'production'
})

package.json package.json

{
  "name": "my-module-name",
  "version": "1.0.0-beta.1",
  "description": "",
  "main": "dist/main/index.js",
  "scripts": {
    "start": "webpack-dev-server --config webpack.dev.js",
    "server": "node src/server",
    "format": "prettier-standard 'src/**/*.js'",
    "lint": "eslint src",
    "build": "webpack --config webpack.prod.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Liran",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "babel-preset-env": "^1.7.0",
    "clean-webpack-plugin": "^0.1.19",
    "css-loader": "^0.28.11",
    "eslint": "^4.19.1",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "html-webpack-plugin": "^3.2.0",
    "idempotent-babel-polyfill": "^0.1.1",
    "node-sass": "^4.9.0",
    "prettier-standard": "^8.0.1",
    "sass-loader": "^7.0.1",
    "style-loader": "^0.21.0",
    "uglifyjs-webpack-plugin": "^1.2.5",
    "webpack": "^4.6.0",
    "webpack-cli": "^2.0.15",
    "webpack-dev-middleware": "^3.1.3",
    "webpack-dev-server": "^3.1.3",
    "webpack-merge": "^4.1.2"
  }
}

Any help/pointers would be greatly appreciated.任何帮助/指针将不胜感激。 If you need more information, please let me know.如果您需要更多信息,请告诉我。

If you are not the library author and are having a problem consuming another library, you may be seeing an error like this:如果您不是库的作者并且在使用另一个库时遇到问题,您可能会看到如下错误:

TypeError: [LIBRARY_NAME]__WEBPACK_IMPORTED_MODULE_3__ is not a constructor

If that's the case, you may be importing the library incorrectly in your code (it may be a problem with default exports).如果是这种情况,您可能在代码中错误地导入了库(这可能是默认导出的问题)。 Double check the library docs for usage.仔细检查库文档以了解使用情况。

It may be as simple as changing this:这可能就像改变这个一样简单:

import Foo from 'some-library/Foo';

to this:对此:

import { Foo } from 'some-library';

It is not working because it is missing libraryTarget and library properties.它不起作用,因为它缺少libraryTarget and library属性。 By doing that webpack know which format of module you would like to create, ie: commonjs ( module.exports ) or es ( export ).通过这样做,webpack 知道您想要创建哪种格式的模块,即:commonjs ( module.exports ) 或 es ( export )。

I would do something like:我会做这样的事情:

...
  output: {
    path: path.join(__dirname, 'dist'),
    filename: path.join('[name]', 'index.js'),
    library: "my-library",
    libraryTarget: "umd" // exposes and know when to use module.exports or exports.
  },
...

Besides setting the libraryTarget<\/code> , it may also be necessary to move the export<\/code> in the JavaScript file to the default.除了设置libraryTarget<\/code> ,可能还需要将 JavaScript 文件中的export<\/code>移动到默认值。

function MyClassName() {
  ...
}

export default MyClassName;

For me, it was the cache issue.对我来说,这是缓存问题。 Just cleared the cookies, cache data and closed, reopened the browser.刚刚清除了cookies,缓存数据并关闭,重新打开浏览器。 It worked.有效。

Cf.参见David Calhoun's answer , if you run into this with a third-party library, you may be trying to import a CommonJS module as an ECMAScript module . David Calhoun 的回答,如果您使用第三方库遇到此问题,您可能正在尝试将CommonJS 模块作为ECMAScript 模块导入。 The workaround there seems to be to use require instead of import , eg, instead of解决方法似乎是使用require而不是import ,例如,而不是

import { Foo } from 'bar'

you need to write你需要写

const Foo = require('bar')

(There may be a more elegant way to handle this, but this is what worked for me.) (可能有一种更优雅的方法来处理这个问题,但这对我有用。)

I had the same error message and discovered that the cause was circular import statements.我有同样的错误信息,发现原因是循环导入语句。 That is: I had two files that imported each other, wherein one file contained an export default class<\/code> that contained a method that was dependent upon an export function<\/code> from the other file.也就是说:我有两个相互导入的文件,其中一个文件包含一个export default class<\/code> ,该类包含一个依赖于另一个文件的export function<\/code>的方法。 My solution was to move one of the dependencies (functions) out of the class and into a utils.js<\/code> file, which was a more appropriate place for it anyway!我的解决方案是将其中一个依赖项(函数)移出类并放入utils.js<\/code>文件中,无论如何这是一个更合适的地方!

"

In my case, the error was being caused in React when trying to invoke JS's built-in Error constructor, or in other words, basically when calling throw new Error("something") .在我的例子中,当尝试调用 JS 的内置Error构造函数时,或者换句话说,基本上是在调用throw new Error("something")时,React 中导致了错误。

On inspection of my code, I realised I had a component called Error in my project which was being imported into the same file.在检查我的代码时,我意识到我的项目中有一个名为Error的组件,它被导入到同一个文件中。 The name clash between this component and JS's built-in Error constructor was causing the error mentioned in the question.该组件与 JS 的内置Error构造函数之间的名称冲突导致了问题中提到的错误。

In case something is using wepack 5 + babel 7如果某些东西正在使用 wepack 5 + babel 7

"webpack": "5.73.0",
"@babel/core": "7.4.4",
"@babel/preset-env": "7.4.4",
"babel-loader": "8.0.5",

AND want to use class instead function , this worked for me:并且想使用class而不是function ,这对我有用:

class Person {
   constructor(fname, lname, age, address) {
      this.fname = fname;
      this.lname = lname;
      this.age = age;
      this.address = address;
   }

   get fullname() {
      return this.fname +"-"+this.lname;
   }
}

export default Person;

In my case .babelrc was not necesary在我的情况下.babelrc 不是必需的

tl;dr tl;博士

Make sure that you import properly through index files.确保通过索引文件正确导入。

Explanation解释

For me, this error was caused by importing through index files.对我来说,这个错误是由通过索引文件导入引起的。 I had multiple directories with their index.ts files that exported all the files inside the directory.我有多个目录,其中包含导出目录中所有文件的index.ts文件。 These index files were accumulated/reexported by a main index.ts file so everything can be imported through it.这些索引文件由主index.ts文件累积/重新导出,因此所有内容都可以通过它导入。

src/
├── index.ts
├── module1/
│   ├── index.ts
│   ├── file1.ts
│   └── file2.ts
└── module2/
    ├── index.ts
    ├── file3.ts
    └── file4.ts

In file4.ts I had an import like this:file4.ts ,我有一个这样的导入:

import { file1Class, file2Class, file3Class } from "src";

I had to split it into two separate imports:我不得不将它分成两个单独的导入:

import { file1Class, file2Class } from "src/module1";
import { file3Class } from "src/module2";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 _plugins_vuetify__WEBPACK_IMPORTED_MODULE_136 __。默认不是构造函数 - _plugins_vuetify__WEBPACK_IMPORTED_MODULE_136__.default is not a constructor WebpackError: TypeError: p5__WEBPACK_IMPORTED_MODULE_4___default.a 不是构造函数 - WebpackError: TypeError: p5__WEBPACK_IMPORTED_MODULE_4___default.a is not a constructor Webpack 导入 Keycloak 时导入的模块不是 VueJS 中的构造函数 - Webpack Imported Module is not a Constructor in VueJS when Importing Keycloak 未捕获的类型错误:_models_Search__WEBPACK_IMPORTED_MODULE_0___default.a 不是构造函数 - Uncaught TypeError: _models_Search__WEBPACK_IMPORTED_MODULE_0___default.a is not a constructor 未捕获的类型错误:__WEBPACK_IMPORTED_MODULE_7__vanilla_tabs__ 不是构造函数 - Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_7__vanilla_tabs__ is not a constructor 打字稿| TypeError:__ WWEPACK_IMPORTED_MODULE_1_signature_pad__不是构造函数 - Typescript | TypeError: __WEBPACK_IMPORTED_MODULE_1_signature_pad__ is not a constructor “TypeError:chart_js__WEBPACK_IMPORTED_MODULE_9__.default 不是构造函数” - "TypeError: chart_js__WEBPACK_IMPORTED_MODULE_9__.default is not a constructor" 如何修复TypeError:application_module__WEBPACK_IMPORTED_MODULE_1 ___ default.a不是构造函数 - How to fix TypeError: application_module__WEBPACK_IMPORTED_MODULE_1___default.a is not a constructor 类型错误:Webpack 导入的模块不是 function - TypeError: Webpack imported module is not a function 使用WebPack + TypeScript定义导入的外部模块 - Defining an imported external module with WebPack + TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM