【问题标题】:` __webpack_require__(...) is not a function` when using babel 6` __webpack_require__(...) is not a function` 使用 babel 6 时
【发布时间】:2016-02-14 11:47:37
【问题描述】:

一切似乎都很好:http://d.pr/i/1aZxR 使用以下配置。

但是,当我运行代码时,我收到以下错误(通过 webpack-dev-server):

Uncaught TypeError: __webpack_require__(...) is not a function(anonymous function) @ login.js:4__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50(anonymous function) @ bootstrap.js:2363__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50(anonymous function) @ app.38790ff45722f55eb700.js:29__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50webpackJsonpCallback @ bootstrap 38790ff45722f55eb700?6a08:21(anonymous function) @ app.38790ff45722f55eb700.js:1
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.7/$injector/nomod?p0=app
    at http://localhost:3000/vendor.js:193:13
    at http://localhost:3000/vendor.js:2111:18
    at ensure (http://localhost:3000/vendor.js:2035:39)
    at module (http://localhost:3000/vendor.js:2109:15)
    at http://localhost:3000/vendor.js:4515:23
    at forEach (http://localhost:3000/vendor.js:461:21)
    at loadModules (http://localhost:3000/vendor.js:4499:6)
    at createInjector (http://localhost:3000/vendor.js:4424:12)
    at doBootstrap (http://localhost:3000/vendor.js:1782:21)
    at bootstrap (http://localhost:3000/vendor.js:1803:13)
http://errors.angularjs.org/1.4.7/$injector/modulerr?p0=app&p1=Error%3A%20%…%20at%20bootstrap%20(http%3A%2F%2Flocalhost%3A3000%2Fvendor.js%3A1803%3A13)(anonymous function) @ angular.js:68(anonymous function) @ angular.js:4413forEach @ angular.js:336loadModules @ angular.js:4374createInjector @ angular.js:4299doBootstrap @ angular.js:1657bootstrap @ angular.js:1678angularInit @ angular.js:1572(anonymous function) @ angular.js:28899fire @ jquery.js:3099self.fireWith @ jquery.js:3211jQuery.extend.ready @ jquery.js:3417completed @ jquery.js:3433

我认为 babel 在某种程度上干扰了__webpack_require__,但我不确定。我确实尝试过使用不同的转换/插件,但我找不到解决方案。

.babelrc:

{
  "plugins":[
    "transform-runtime",
    "transform-node-env-inline"
  ],
  "presets":[
    "stage-0",
    "es2015"
  ]
}

这是我的 webpack.config.js:

var Clean = require('clean-webpack-plugin');
var CompressionPlugin = require("compression-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
var path = require('path');
var StatsPlugin = require('stats-webpack-plugin');
var webpack = require('webpack');

//CONSTANTS

var NODE_ENV = process.env.NODE_ENV;
var IS_DEV = NODE_ENV === 'development';
var babelFile = fs.readFileSync('./.babelrc', 'utf8');
var BABELRC = JSON.parse(babelFile);
var cleanFonts = function(){
  return new Clean(['dist/tmp/*.{ttf,eot,svg,woff}']);
}
var cleanImages = function(){
  return new Clean(['dist/tmp/*.{png,jpg}']);
}
var cleanJs = function(){
  return new Clean(['dist/*.{js,map}']);
}
var plugins = [
  new webpack.NoErrorsPlugin(),
  cleanJs(),
  // new StatsPlugin('stats.json', {chunkModules: true}),
  new webpack.ProvidePlugin({$: "jquery",jQuery: "jquery","window.jQuery": "jquery" }),
  new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
  new HtmlWebpackPlugin({
    template: 'client/app/vendors/assets/index-tmpl.html',
    filename: 'index.html'
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    filename: 'vendor.js',
    chunks:['customer','personalOrganization','app']
  })
  // new ngAnnotatePlugin({add: true})
  // new ExtractTextPlugin("style.[hash].css", {
  //    disable: false,
  //    allChunks: true
  // }),

  //new webpack.optimize.CommonsChunkPlugin({minChunks: 2, children: true, async: true}),
  // new CompressionPlugin({asset: "{file}.gz", algorithm: "gzip", regExp: /\.js$|\.html$/, threshold: 10240, minRatio: 0.8 })
];
var dev_plugins = [
]
var prod_plugins = [
  cleanFonts(),
  cleanImages(),
  new webpack.optimize.UglifyJsPlugin({
    minimize: true,
    sourceMap: false,
    compress: { warnings: false },
    mangle: false
  }),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.AggressiveMergingPlugin()
];
if(NODE_ENV !== 'development'){
  plugins = plugins.concat(prod_plugins);
}
else{
  plugins = plugins.concat(dev_plugins);
}
babelLoaderOpts = {
  cacheDirectory: true
};
Object.assign(babelLoaderOpts, BABELRC);
module.exports = {
  cache: IS_DEV,
  // watch: IS_DEV,
  devtool: 'source-map',
  entry: {
    "app": "./client/app/app.js",
    "devserver": 'webpack-dev-server/client?http://localhost:3000'
  },
  output: {
      path: __dirname + "/dist",
      filename: '[name].[hash].js'
  },
  module: {
        noParse: [
          /moment.js/
        ],
        loaders: [
            { test: require.resolve("jquery"), loader: "expose?$!expose?jQuery" },
            {
              test: /\.js$/,
              exclude: /(node_modules|bower_components|vendors)/,
              loader: 'babel',
              query: babelLoaderOpts
            },
            { test: /\.html$/, loader: 'raw' },
            { test: /\.scss$/, loader: "style!css!sass?outputStyle=expanded"+"&includePaths[]=" + path.resolve(__dirname, "./node_modules/compass-mixins/lib")},
            { test: /\.css$/,  loader: 'style!css' },
            { test: /\.(png|jpeg|jpg|gif)$/, loader: 'url-loader?limit=30000&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.woff(\?\S*)?$/,  loader : 'url?prefix=font/&limit=10000&mimetype=application/font-woff&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.woff2/, loader: 'url?prefix=font/&limit=100000&mimetype=application/font-woff2&name=tmp/[name].[ext]&no_emit_env=development' },
            { test: /\.ttf/,   loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.eot/,   loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.svg/,loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            //{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true&&includePaths[]='+ path.resolve(__dirname, './node_modules/compass-mixins/lib')) },
            //{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
      ]
  },
  devServer: {
    contentBase: './client/app'
  },
  resolve: {
      modulesDirectories: ['vendors','node_modules', 'bower_components'],
      extensions: ['', '.js', '.json']
  },
  plugins: plugins
};

【问题讨论】:

  • 当我尝试直接从 require require('module-test')(); 调用函数但模块返回不是函数时出现这样的错误;
  • 还有一个,如果你尝试在 ES6 语法中使用require(''),babel-loader 会返回对象。请改用import
  • 我也有同样的问题。我的项目是 98% 的 AMD 模块和 2% 的新 ES6 模块。我想逐渐转向 ES6,但如果我需要修改所有使用新 ES6 模块的模块,这很难。在 Babel 5 中运行良好。
  • 关于这个问题的任何更新?当我使用“watch”编译时,其他编译都会发生这种情况。要“修复”它,我需要从头开始重建,而不是使用“watch”,这会浪费大量时间。

标签: webpack babeljs webpack-dev-server


【解决方案1】:

我的情况与上面@William 给出的答案正好相反。 包括 {} import mapActions from 'vuex' 帮助了我。 如:

import { mapActions } from 'vuex'

【讨论】:

  • 我不知道为什么,但如果它不起作用,您可以通过移除大括号来进行更改。使用大括号对我有用,但对于以前没有大括号的项目工作正常。
【解决方案2】:

我的 webpack 遇到了这个问题,因为我正在为 web 和 node 构建我的项目,并且我在 entry 中都使用了 isomorphic-unfetch

我通过将 isomorphic-unfetch 替换为适当的 fetch 来修复它:unfetch 用于 web 和 node-fetch 用于 nodejs

webpack.config.js

module.exports = [
  {
    entry: ['unfetch', 'regenerator-runtime/runtime', './lib/app.js'],
    ...
  },
  {
    entry: ['node-fetch', 'regenerator-runtime/runtime', './lib/app.js'],
    target: 'node',
    ...
  },
];

【讨论】:

    【解决方案3】:

    我有同样的问题。解决方案是从require语句切换,例如

    let fs = require("fs");
    

    通过进口

    import * as fs from 'fs';
    

    您还可以通过 webpack 配置中的 externals 数组公开所有 Node 模块。由于它们是通过 Webpack 外部提供的,因此不必要求它们,而是将它们与导入一起使用。

    module.exports = {
       "externals": {
          "electron": "require('electron')",
          "child_process": "require('child_process')",
          "fs": "require('fs')",
          "path": "require('path')",
          ...
       }
    }
    

    您可以在my article 中阅读有关此问题的更多信息。

    【讨论】:

    • 嗨,这摆脱了原来的问题,但我面临着另一个问题。任何想法:Uncaught ReferenceError: require is not defined
    • @Mr.Benedict 这可能是因为 Web 不支持 require 。您可以尝试target: 'node',但这不适用于前端(网络)。
    • 感谢您的解决方案,不幸的是,我在 Module../src/index 的 eval (index.js:8) 处的 readFromDataFile (readdata.js:8) 处遇到了另一个运行时错误 readdata.js:8 Uncaught TypeError: Cannot read property 'readFileSync' of undefined .js (bundle.js:109) 在 webpack_require (bundle.js:20) 在 bundle.js:84 在 bundle.js:87 readFromDataFile @ readdata.js:8 (anonymous) @ index.js js:8 ./src/index.js @bundle.js:109 webpack_require @bundle.js:20(匿名)@bundle.js:84(匿名)@bundle.js:87跨度>
    【解决方案4】:

    我想补充一下为什么会弹出这个错误的另一个原因:

    我做了以下事情:

    import mapActions from 'vuex'
    

    代替:

    import { mapActions } from 'vuex'
    

    前者是导入整个vuex 导出,这是一个对象。添加对象解构解决了这个问题。

    【讨论】:

    • 这让我走上了正确的道路 - 我正在导出一个默认对象,然后尝试以 importedObj() 执行它
    【解决方案5】:

    我通过在我的 webpack.config 中添加缺少的加载程序解决了类似的问题。不知道为什么这可以解决问题,但您可能想看看是否还缺少加载程序。

    (要明确一点——当我将库降级到早期版本时,我最初发现问题出在加载器上。Webpack 错误消息说缺少 json 加载器,所以我将以下内容添加到我的配置,然后能够回到最新版本:

    module:{
    loaders : [
      {
          test: /\.json$/,
          loader: "json-loader"
        }
    ]
    }
    

    )

    【讨论】:

      【解决方案6】:

      我有同样的错误。在处理 es6 模块时,应该使用 require(...).default

      例如:

      const angular = require('angular');
      const ngModule = angular.module('app', []);
      require('./directives').default(ngModule);
      // or
      var kgdir = require('./directives').default;
      kgdir(ngModule);
      

      不过,babel-plugin-add-module-exports 也应该可以工作。

      您可以查看此页面:github webpack issues 1685

      【讨论】:

        【解决方案7】:

        我认为从 require 切换到 import 的建议解决方案是不正确的。导入需要在文件的顶部进行,因此您不能让您的生产构建省略 devtools。你想要一个条件要求。

        我认为babel-plugin-add-module-exports 解决了这个问题。看看这个react-redux-starter-kit,看看它是如何在项目中使用的。

        【讨论】:

        • 那个插件对我不起作用..仍然得到同样的错误。
        【解决方案8】:

        在我的 webpack-dev-server 入口文件中更新到 Babel 6 后,我遇到了类似的问题。正如@Serhey 在 cmets 中提到的,我通过从 require 切换到 import 解决了我的问题,即 require('./devTools)(store);import devTools from './devTools'; devTools(store);

        【讨论】:

          猜你喜欢
          • 2018-08-23
          • 2019-07-20
          • 1970-01-01
          • 2017-10-04
          • 1970-01-01
          • 2019-11-10
          • 1970-01-01
          • 2019-01-16
          • 1970-01-01
          相关资源
          最近更新 更多