Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uncaught TypeError: Cannot read property 'call' of undefined #8996

Closed
xwchris opened this issue Apr 3, 2019 · 22 comments

Comments

Projects
None yet
9 participants
@xwchris
Copy link

commented Apr 3, 2019

Bug report

What is the current behavior?
In webpack production mode, bundled file has error when running in the browser.

If the current behavior is a bug, please provide the steps to reproduce.

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: './index.js',
  output: {
    filename: '[name].[hash:5].js',
    path: path.resolve(__dirname, 'public'),
    publicPath: '/'
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: 'babel-loader'
      }
    ]
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        react: {
          test: /\/node_modules\/react/,
          name: 'react',
          priority: 1
        },
        vendors: {
          name: 'vendors',
        }
      },
    },
  },
  devServer: {
    contentBase: path.resolve(__dirname, 'public'),
    hot: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './index.html'
    })
  ]
}

.babelrc

{
  "presets": [[
    "@babel/env",
    {
      "targets": {
        "esmodules": true
      },
      "modules": false
    }
  ],"@babel/react"],
  "plugins": [
    "@babel/plugin-syntax-dynamic-import"
  ]
}

index.js

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { render } from 'react-dom';
import App from './App';

render((
  <BrowserRouter>
    <App />
  </BrowserRouter>
), document.getElementById('root'));

App.js

import React from 'react';

const App = () => (
  <div>
  </div>
);

export default App

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>todo app</title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

and here is the react and react-router version

"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-router": "^5.0.0",
"react-router-dom": "^5.0.0",

After bundled these file, open this in browser, got error like following
image

I found some moduleId is null in bootstrap.js

image

but in mode: 'development', everything is ok!

What is the expected behavior?
no any error

Other relevant information:
webpack version: v4.29.6
Node.js version: v8.11.3
Operating System: Macos mojave v10.14 (18A391)
Additional tools: none

@evilebottnawi

This comment has been minimized.

Copy link
Member

commented Apr 3, 2019

@xwchris i think we already fix this problem, but not released, can you test this using dc26688?

@xwchris

This comment has been minimized.

Copy link
Author

commented Apr 3, 2019

@evilebottnawi I have tested the case with dc26688,but I'm sorry it's still has the error as I mentioned before.

@evilebottnawi

This comment has been minimized.

Copy link
Member

commented Apr 3, 2019

Can you create minimum reproducible test repo?

@xwchris

This comment has been minimized.

Copy link
Author

commented Apr 3, 2019

@evilebottnawi I create the test repo webpack-issue-8996 here

@evilebottnawi

This comment has been minimized.

Copy link
Member

commented Apr 3, 2019

@xwchris thanks for issue, looks like a bug, feel free to send a PR

xwchris pushed a commit to xwchris/webpack that referenced this issue Apr 4, 2019

@xwchris xwchris referenced this issue Apr 4, 2019

Closed

fixes #8996 #9002

@xwchris

This comment has been minimized.

Copy link
Author

commented Apr 4, 2019

@evilebottnawi I think I have found the reason of the problem.

With the webpack's config above, SplitChunksPlugin extracts the entryModule of chunk main and add it to the chunk vendors, but main still has reference of entryModule. Then ModuleConcatenationPlugin concatenate modules in vendors which include the entryModule and form a new concated module. So modules list have not entryModule any more and can't assign id to it.

I don't know wether I expressed myself correctly. I try to send a PR which avoid bundle entryModule to common chunks, but the logic maybe not right and can't pass all tests.

I want to know what's the right logic and I can help to fix it.

@sokra

This comment has been minimized.

Copy link
Member

commented Apr 8, 2019

This should be fixed by #8916

Could you check this?

@xwchris

This comment has been minimized.

Copy link
Author

commented Apr 9, 2019

@sokra I test with #8916 and it works now.

@xwchris xwchris closed this Apr 9, 2019

@baiyuze

This comment has been minimized.

Copy link

commented Apr 12, 2019

@sokra I test with #8916 and it works now.

I used the latest version of webpack@4.29.6, and still had this problem. And I'm not using config. Optimization either.

Here is my webpack configuration

const fs = require('fs')
const os = require('os')
const path = require('path')
const webpack = require('webpack')

const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')

// 根据构建环境设置参数 
let isdev = true
let htmlOut = path.join(__dirname, 'public/dist/index.html')
// let htmlOut = 'index.html'

if (process.env.NODE_ENV !== "development") {
  isdev = false
}

let pkg = require('./package.json')
let theme = pkg.theme

let output = {
  path: path.resolve(__dirname, './public/dist/common'),
  // chunkFilename: `[name].js`,
  filename: `[name].js`,
  publicPath: '/common/'
}

let imgOptions = {
  name: 'img/[name].[ext]',
  limit: 10000
};

if (isdev) {
  htmlOut = 'index.html'

  output.publicPath = './'
}

//复制文件
let entryBase = [path.join(__dirname, './src/index.js')]

let plug = ['lodash', 'moment']
let config = {
  entry: {
    plug,
    county: entryBase,
  },
  output,
  module: {
    rules: [
      {
        test: /\.(jsx|js)?$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react',
              ['@babel/preset-env', {
                "targets": {
                  "browsers": [
                    "ie >= 9",
                    "ff >= 30",
                    "chrome >= 34",
                    "safari >= 7",
                    "opera >= 23",
                    "bb >= 10"
                  ]
                }
              }]
            ],
            plugins: [
              [
                "import",
                { libraryName: "antd", style: true }
              ]
            ]
          }
        }
      },
      {
        test: /\.(scss|css|less)$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                require('precss'),
                require('autoprefixer')
              ],
            }
          },
          {
            loader: 'less-loader',
            options: {
              javascriptEnabled: true,
              modifyVars: theme   //antd默认主题样式
            }
          }
        ],
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
            options: {
              minimize: true
            }
          }
        ]
      },
      {
        test: /\.(png|jpg|gif|webp|svg)$/,
        use: [
          {
            loader: 'url-loader',
            options: imgOptions
          }
        ]
      }
    ]
  },
  resolve: {
    alias: {
      components: path.resolve(__dirname + '/src/components'),
      config: path.resolve(__dirname + '/src/config'),
      utils: path.resolve(__dirname + '/src/utils'),
      pages: path.resolve(__dirname + '/src/pages')
    },
    extensions: ['.js', '.jsx']
  },
  mode: process.env.NODE_ENV,
  plugins: [
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',  // 目标文件名
      algorithm: 'gzip',          // 使用gzip压缩
      test: new RegExp(
        '\\.(js|css)$'            // 压缩 js 与 css
      ),
      threshold: 10240,           // 资源文件大于10240B=10kB时会被压缩
      minRatio: 0.8               // 最小压缩比达到0.8时才会被压缩
    }),
    // 提取样式,生成单独文件
    new MiniCssExtractPlugin({
      filename: `[name].css`,
      // chunkFilename: `[name].antd.css`
    }),

    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
      filename: htmlOut,            // 通过模板生成的文件名
      template: './index.ejs',       // 模板路径
      inject: true,                 // 是否自动在模板文件添加 自动生成的js文件链接
      title: '知县',
      compress: true,
      minify: {
        removeComments: true        // 是否压缩时 去除注释
      },
    }),

  ],

  // 提供静态服务
  devServer: {
    port: 8004,
    historyApiFallback: true,
    contentBase: false,
    publicPath: '/',
    compress: true,                                       // 是否使用gzip
    headers: {                                            // 添加头部信息
      "X-Custom-Foo": "bar"
    },
    open: true,
    proxy: {                                              // 请求代理
      "/proxy/*": {
        // target: "http://192.168.0.130:91",                // 代理
        target: "http://10.56.202.29:7071",                // 代理
        changeOrigin: true,
        pathRewrite: {
          '^/proxy': ''
        }
      }
    },

  }
}


if (isdev) {
} else {
  // config.optimization = {
  //   minimizer: [
  //     new UglifyJsPlugin({
  //       cache: true,
  //       parallel: true,
  //       sourceMap: false
  //     }),
  //   ],
  //   splitChunks: {
  //     cacheGroups: {
  //       common: {
  //         name: 'common',
  //         chunks: 'all',
  //         // chunksSortMode:'dependency',
  //         priority: 2,
  //         minChunks: 2,
  //       },
  //       utils: { // 抽离自定义公共代码
  //         test: /\.jsx$/,
  //         chunks: 'all',
  //         name: 'utils',
  //         minSize: 0 // 只要超出0字节就生成一个新包
  //       }
  //     }
  //   }
  // }
}

module.exports = config

Here is my .babelrc configuration

{
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-transform-runtime"],
    ["@babel/plugin-proposal-class-properties",{ "loose" : true }],
    ["@babel/plugin-syntax-dynamic-import"],
    ["import", {
      "libraryName": "antd",
      "libraryDirectory": "es",
      "style": true
    }]
  ]
}

webpack@4.29.6
webpack-cli@3.1.3

1555040760639_图片

Did I miss something?

Please let me know. Thank you

@xwchris

This comment has been minimized.

Copy link
Author

commented Apr 12, 2019

@baiyuze The issue has been fixed, but not release.

@CosminIonascu

This comment has been minimized.

Copy link

commented Apr 12, 2019

@xwchris when it will be released? Can we test on an unreleased version? I'm having the same problem thanks

@baiyuze

This comment has been minimized.

Copy link

commented Apr 12, 2019

@baiyuze The issue has been fixed, but not release.

如果直接使用github最新代码应该是OK的吧?

@nailfar

This comment has been minimized.

Copy link

commented Apr 12, 2019

@baiyuze 然而并不是的,哈哈哈 。我看了下代码和merge的代码不一致;可以去提交pr 的那个人仓库里去安装 他的版本,暂时修复,等release 之后再处理吧

@baiyuze

This comment has been minimized.

Copy link

commented Apr 12, 2019

@baiyuze 然而并不是的,哈哈哈 。我看了下代码和merge的代码不一致;可以去提交pr 的那个人仓库里去安装 他的版本,暂时修复,等release 之后再处理吧

@nailfar 我记得这个问题在去年就有了,为什么现在一直没有处理。。。
有啥方法能够避过这个坑吗?

@nailfar

This comment has been minimized.

Copy link

commented Apr 12, 2019

@baiyuze concatenateModules:false

@xwchris

This comment has been minimized.

Copy link
Author

commented Apr 12, 2019

@CosminIonascu @baiyuze the latest code of master can work. To avoid this, you can use concatenateModules:false to disabled ModuleConcatenationPlugin like @nailfar mentioned.

@baiyuze

This comment has been minimized.

Copy link

commented Apr 12, 2019

@CosminIonascu @baiyuze最新的高手代码可以工作。为避免这种情况,您可以像@nailfar一样使用concatenateModules:false禁用。ModuleConcatenationPlugin

This really does solve the problem. thank you

@evilebottnawi

This comment has been minimized.

Copy link
Member

commented Apr 12, 2019

It is not released yet

@tobiasfrei

This comment has been minimized.

Copy link

commented May 13, 2019

still not released? same error on import paperjs/core with webpack 4.29.6 in prod mode.

@pantoninho

This comment has been minimized.

Copy link

commented May 22, 2019

I'm experiencing the same issue. The error only appears in production mode on webpack@4.32.1.

@CosminIonascu

This comment has been minimized.

Copy link

commented May 22, 2019

I've resolved this by adding chunk name for each dynamic import import(/* webpackChunkName: 'Filename' */ '../filename')
add also adding this in webpack config optimization: { namedModules: true, namedChunks: true, splitChunks: { cacheGroups: { default: false } } }

@pantoninho

This comment has been minimized.

Copy link

commented May 22, 2019

@CosminIonascu I already had all my chunks named in the dynamic import, but I was missing those optimization options.

Thanks for the tip, it fixed my problem!

Shouldn't this issue be re-opened though?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.