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

时间:2018-05-20 13:19:37

标签: javascript npm webpack babel es6-modules

我创建了一个小型JS模块,我打算制作一个npm包,但现在只是在GitHub上。这个模块是用ES6和SCSS编写的,因此依赖于webpack和babel进行转换。

为了测试它,我创建了一个具有类似设置的单独项目(webpack和babel)。在安装我的模块后,在尝试将其导入我的index.js时,Chrome Developer Tools中出现以下错误:( 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

我已经看过无数的答案并尝试了无数的解决方案,但无济于事。我的模块设置如下。

.babelrc

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

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

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

{
  "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"
  }
}

任何帮助/指针将不胜感激。如果您需要更多信息,请告诉我。

4 个答案:

答案 0 :(得分:12)

如果您不是图书馆作者,并且在使用其他图书馆时遇到问题,则可能会看到如下错误:

TypeError: [LIBRARY_NAME]__WEBPACK_IMPORTED_MODULE_3__ is not a constructor

如果是这种情况,则可能是您在代码中错误地导入了库(这可能是默认导出的问题)。仔细检查库文档的用法。

只需更改此内容即可

import Foo from 'some-library/Foo';

对此:

import { Foo } from 'some-library';

答案 1 :(得分:6)

它不起作用,因为它缺少libraryTarget and library属性。通过这个webpack知道你想要创建哪种模块格式,即:commonjs(module.exports)或es(export)。

我会做类似的事情:

...
  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.
  },
...

答案 2 :(得分:0)

参见David Calhoun's answer,如果您在使用第三方库时遇到此问题,您可能正在尝试将 CommonJS module 作为 ECMAScript module 导入。解决方法似乎是使用 require 而不是 import,例如,而不是

import { Foo } from 'bar'

你需要写

const Foo = require('bar')

(可能有更优雅的方法来处理这个问题,但这对我有用。)

答案 3 :(得分:0)

除了设置 libraryTarget 之外,可能还需要将 JavaScript 文件中的 export 移动到默认值。

function MyClassName() {
  ...
}

export default MyClassName;

然后在 webpack 配置中库类型 umd ...

(请注意,我使用了较新的 library.type 而不是较旧的 libraryTarget(请参阅 https://webpack.js.org/configuration/output/#outputlibrarytarget)。

 const path = require('path');
 
 module.exports = {
    mode: "production",
    entry: '../wherever/MyClassName.js',
    
    output: {
        library: {
          name: "MyClassName",
          type: "umd",  // see https://webpack.js.org/configuration/output/#outputlibrarytype
          export: "default",  // see https://github.com/webpack/webpack/issues/8480
        },
        filename: 'MyClassName.min.js',
        path: path.resolve(__dirname, '../wherever/target/')
    },
    optimization: {
        minimize: true
    }
 };

export default 使类在 JavaScript 中可用,就像直接嵌入文件一样,即

<script type="text/javascript" src="MyClassName.min.js"></script>
<script type="text/javascript">
<!--

var myInstance = new MyClassName();

// -->
</script>

免责声明:即使最初的问题已经三年了,我还是添加了这个答案。遇到“不是构造函数”的问题后,我花了好几个小时才找到 default 的解决方案。那是第二次,我搜索并找到了 :D