42

Everything seems to build fine: http://d.pr/i/1aZxR with the following configs.

However, when I run the code I get the following error this (via 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

I think babel is interfering with __webpack_require__ in some way but I'm not sure. I did try using different transforms/plugins but I wasn't able to find a solution.

.babelrc:

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

here's my 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
};
Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
chuliamiz
  • 421
  • 1
  • 4
  • 4
  • 1
    I got such error when I try invoke function directly from require `require('module-test')();` but module return not a function; – Serhiy Nov 19 '15 at 19:03
  • And one more, if you try to use `require('')` with ES6 syntax, babel-loader return object. Use `import` instead. – Serhiy Nov 19 '15 at 19:17
  • 1
    I have the same problem. My project is 98% AMD modules and 2% new ES6 modules. I would like to gradually move to ES6 but it's hard if I need to modify all the modules that use a new ES6 module. Worked nicely in Babel 5. – Ilkka Oksanen Dec 02 '15 at 13:52
  • Any update on this issue? It happens to me every other compilation when I am using the "watch" compilation. To "fix" it, I need to rebuild from scratch instead of using "watch" which is a massive waste of time. – ChrisR Feb 05 '16 at 20:31

8 Answers8

11

I'd like to add another reason why this error might pop up:

I did the following:

import mapActions from 'vuex'

instead of:

import { mapActions } from 'vuex'

The former was importing the entire vuex export, which is an object. Adding object destructuring fixed the problem.

William
  • 161
  • 2
  • 9
6

I had the same error. When dealing with es6 modules, you should use require(...).default

For instance:

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

However, babel-plugin-add-module-exports should also work.

You can check out this page: github webpack issues 1685

kgosse
  • 114
  • 1
  • 4
4

I had a similar issue after updating to Babel 6 in my webpack-dev-server entry file. As mentioned by @Serhey in the comments, I resolved my issue by switching from require to import, i.e., require('./devTools)(store); to import devTools from './devTools'; devTools(store);

LemurDev
  • 71
  • 8
4

I believe the proposed solutions to switch from require to import are not correct. Imports need to happen at the top of the file and therefor you can't have your production build omit the devtools. You want a conditional require.

I think babel-plugin-add-module-exports solves the problem. Have a look at this react-redux-starter-kit to see how it's used in a project.

Thijs Koerselman
  • 21,680
  • 22
  • 74
  • 108
2

I had the same issue. The solution was to switch from require statements, such as

let fs = require("fs");

to imports via

import * as fs from 'fs';

You can also expose all Node modules via the externals array in your webpack config. Since they are provided through the Webpack externals, one does not have to require them but use them with imports.

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

You can read more about this problem in my article.

Matthias Sommer
  • 1,070
  • 13
  • 28
  • Hi, this got rid of the original issue but I'm faced with another. Any ideas: `Uncaught ReferenceError: require is not defined` – Mr. Benedict Nov 25 '17 at 11:15
  • @Mr.Benedict that's probably because require is not supported in Web. You can try `target: 'node'` but that wouldn't work on front-end (web). – Eksapsy Mar 26 '18 at 11:33
  • Thanks, for the solution, Unfortunately, I encountered another runtime error `readdata.js:8 Uncaught TypeError: Cannot read property 'readFileSync' of undefined` at readFromDataFile (readdata.js:8) at eval (index.js:8) at Module../src/index.js (bundle.js:109) at __webpack_require__ (bundle.js:20) at bundle.js:84 at bundle.js:87 readFromDataFile @ readdata.js:8 (anonymous) @ index.js:8 ./src/index.js @ bundle.js:109 __webpack_require__ @ bundle.js:20 (anonymous) @ bundle.js:84 (anonymous) @ bundle.js:87 – Praveer Kumar May 20 '19 at 01:12
1

My case is just the reverse of the answer given by @William above. Including {} in import mapActions from 'vuex' helped me. As:

import { mapActions } from 'vuex'
anil shrestha
  • 2,136
  • 2
  • 12
  • 26
  • I don't know why but if it does not work you can alter by removing braces. Works for me with braces but for previous project without braces was working fine. –  Jul 07 '20 at 14:58
0

I solved a similar issue by adding a missing loader into my webpack.config. No idea why this solves the issue, but you may want to see if you're missing a loader as well.

(Just to be clear - I originally found out that problem was with a loader when I downgraded the library causing the issue to an earlier version. Webpack error messages said that a json loader was missing, so I added the following to my config, and then was able to go back to the newest version:

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

)

Simopaa
  • 449
  • 5
  • 8
0

I had this issue with my webpack because i was building my project for both web and node and I was using isomorphic-unfetch in both the entry.

I fixed it by replacing isomorphic-unfetch with the appropriate fetch: unfetch for web & node-fetch for 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',
    ...
  },
];
Zhong Huiwen
  • 889
  • 13
  • 10