Webpack4 不执行主模块到我的页面入口

Webpack4 does not execute main module to my page entry

当尝试从 webpack 3 迁移到 4 时,一些入口点生成的代码实际上不执行页面的 "main" 模块。

以下示例显示了将使用两个脚本标记加载的生成代码的关键部分。一份用于 vendors.js,一份用于附加条目 las_dlg_projectstatus.js

应该执行的实际代码在 D:\MyDev\ljs_app\periscope_webpack4\build\src\modules\las_dlg_projectstatus\index.js 中,应该在加载具有 ID 86 的模块时加载,但在加载页面时都不会 loaded/executed。

非常感谢任何帮助!

/******/ (function(modules) { // webpackBootstrap
/******/    // install a JSONP callback for chunk loading
/******/    function webpackJsonpCallback(data) {
/******/        var chunkIds = data[0];
/******/        var moreModules = data[1];
/******/        var executeModules = data[2];
/******/        // add "moreModules" to the modules object,
/******/        // then flag all "chunkIds" as loaded and fire callback
/******/        var moduleId, chunkId, i = 0, resolves = [];
/******/        for(;i < chunkIds.length; i++) {
/******/            chunkId = chunkIds[i];
/******/            if(installedChunks[chunkId]) {
/******/                resolves.push(installedChunks[chunkId][0]);
/******/            }
/******/            installedChunks[chunkId] = 0;
/******/        }
/******/        for(moduleId in moreModules) {
/******/            if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/                modules[moduleId] = moreModules[moduleId];
/******/            }
/******/        }
/******/        if(parentJsonpFunction) parentJsonpFunction(data);
/******/        while(resolves.length) {
/******/            resolves.shift()();
/******/        }
/******/
/******/        // add entry modules from loaded chunk to deferred list
/******/        deferredModules.push.apply(deferredModules, executeModules || []);
/******/
/******/        // run deferred modules when all chunks ready
/******/        return checkDeferredModules();
/******/    };
/******/    function checkDeferredModules() {
/******/        var result;
/******/        for(var i = 0; i < deferredModules.length; i++) {
/******/            var deferredModule = deferredModules[i];
/******/            var fulfilled = true;
/******/            for(var j = 1; j < deferredModule.length; j++) {
/******/                var depId = deferredModule[j];
/******/                if(installedChunks[depId] !== 0) fulfilled = false;
/******/            }
/******/            if(fulfilled) {
/******/                deferredModules.splice(i--, 1);
/******/                result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
/******/            }
/******/        }
/******/        return result;
/******/    }
/******/
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // object to store loaded and loading chunks
/******/    // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/    // Promise = chunk loading, 0 = chunk loaded
/******/    var installedChunks = {
/******/        "las_dlg_projectstatus": 0
/******/    };
/******/
/******/    // script path function
/******/    function jsonpScriptSrc(chunkId) {
/******/        return __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".js"
/******/    }
/******/
/******/    var deferredModules = [];
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
/******/    var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
/******/    jsonpArray.push = webpackJsonpCallback;
/******/    jsonpArray = jsonpArray.slice();
/******/    for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
/******/    var parentJsonpFunction = oldJsonpFunction;
/******/
/******/
/******/    // add entry module to deferred list
/******/    deferredModules.push([86,"vendors",3]);
/******/    // run deferred modules when ready
/******/    return checkDeferredModules();
/******/ })
/************************************************************************/
/******/ ({

/***/ "./src/framework/completeness/completeness.js":
/*!****************************************************!*\
  !*** ./src/framework/completeness/completeness.js ***!
  \****************************************************/
/*! exports provided: completnessPercentbar, completnessPercentbarEvent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "completnessPercentbar", function() { return completnessPercentbar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "completnessPercentbarEvent", function() { return completnessPercentbarEvent; });
/* harmony import */ var Source_ODS_ods__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! Source_ODS/ods */ "./src/ods/ods.js");
/* harmony import */ var Source_ODS_convert__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! Source_ODS/convert */ "./src/ods/convert.js");
/* harmony import */ var Source_ODS_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! Source_ODS/ui */ "./src/ods/ui.js");
/* harmony import */ var Source_Framework_backend_jsonData__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! Source_Framework/backend/jsonData */ "./src/framework/backend/jsonData.js");
/* harmony import */ var Source_ODS_ajax__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! Source_ODS/ajax */ "./src/ods/ajax.js");

/* >>>code has been removed to same some space<<< */

/***/ }),

/* >>>most modules have been removed to same some space<<< */

/***/ 86:
/*!*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
  !*** multi core-js/shim regenerator-runtime/runtime <<<...>>> ./src/modules/las_dlg_projectstatus/index.js ./src/modules/las_dlg_projectstatus/index.styl ./src/modules/las_dlg_projectstatus/widget.js ./src/modules/las_dlg_projectstatus/widget.styl ***!
  \*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(/*! core-js/shim */"./node_modules/core-js/shim.js");
__webpack_require__(/*! regenerator-runtime/runtime */"./node_modules/regenerator-runtime/runtime.js");
/* >>>code has been removed to same some space<<< */
__webpack_require__(/*! D:\MyDev\ljs_app\periscope_webpack4\build\src\modules\las_dlg_projectstatus\index.js */"./src/modules/las_dlg_projectstatus/index.js");
__webpack_require__(/*! D:\MyDev\ljs_app\periscope_webpack4\build\src\modules\las_dlg_projectstatus\index.styl */"./src/modules/las_dlg_projectstatus/index.styl");
__webpack_require__(/*! D:\MyDev\ljs_app\periscope_webpack4\build\src\modules\las_dlg_projectstatus\widget.js */"./src/modules/las_dlg_projectstatus/widget.js");
module.exports = __webpack_require__(/*! D:\MyDev\ljs_app\periscope_webpack4\build\src\modules\las_dlg_projectstatus\widget.styl */"./src/modules/las_dlg_projectstatus/widget.styl");


/***/ })

/******/ });
//# sourceMappingURL=las_dlg_projectstatus.js.map

尝试添加一个 script 标签,将您的 vendors.js 加载到您的 html 页面。

我自己也遇到过这个问题。我认为 webpack 假定您加载了所有需要的块,并且仅在加载完成后才启动。看到这些行了吗?

/******/    // add entry module to deferred list
/******/    deferredModules.push([86,"vendors",3]);
/******/    // run deferred modules when ready
/******/    return checkDeferredModules();

看起来像是在说

Hey, this very chunk is ready, but there should also be a chunk named 'vendors' somewhere. I'll check if it's already here (checkDeferredModules), and if it is - I'll start, otherwise I'll pass.

就我而言,我的页面需要 3 个块才能 运行。在我将所有 3 个块都包含到页面 html 之前,它什么也没做。虽然我认为它会异步加载它们。但我想,要使异步块起作用,需要做一些比简单 import from 更聪明的事情。查看 https://webpack.js.org/api/module-methods/#import-

希望对您有所帮助

我想补充显示使用 HtmlWebpackPlugin 的典型配置以供后代使用。

正如 所说,您可能希望使用 HtmlWebpackPlugin 将脚本标签添加到主 HTML 文件中。这是一个扩展通用配置文件的示例生产配置:

const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = merge(common, {
    mode: 'production',
    optimization: {
        splitChunks: {
            chunks: 'all',
        },
    },
    plugins: [
        new HtmlWebpackPlugin(),
    ],
});

Webpack 将在您的 output.path 中生成一个 index.html,它将包含所需的脚本标签,如下所示:

...
<!-- Webpack actually minifies the HTML but I have formatted it here -->
<body>
    <script src="/js/vendors~main.min.js"></script>
    <script src="/js/client.min.js"></script>
</body>
...

如果您使用的是 React 或者您只需要更改生成的 HTML,您可以使用 templates 来生成带有自定义 HTML:[=21= 的输出]

template.html:

<html>
<head>
    <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
    <!-- For my React App -->
    <div id="app></div>
</body>
</html>

webpack.prod.js:

module.exports = merge(common, {
    mode: 'production',
    optimization: {
        splitChunks: {
            chunks: 'all',
        },
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'My title',
            template: 'template.html',
        }),
    ],
});

请注意,该插件会自动 inject 在您的模板底部添加脚本标签 HTML。

我不会写评论,所以让我通过单独的答案来写。 我有同样的问题不是 webpack 本身,而是 webpack-dev-server。脚本在 dev-server 下被冻结,没有其他 webpack 构建包含这个问题。

脚本已添加为单独的入口点,早期供应商的拆分也已配置。

第一个答案描述了冻结脚本内容的问题原因。

所以我的解决方案是为特定块设置忽略供应商缓存组:

...
optimization: {
            splitChunks: {
                minChunks: 1,
                minSize: 30000,
                cacheGroups: {
                    vendor: {
                        name: 'vendor',
                        chunks: (chunk) => chunk.name !== 'organizations',//this line
                        minChunks: 1,
                        test: /[\/]node_modules[\/]/,
                        reuseExistingChunk: false
                    }
                }
            }
}
...

希望有人会觉得有用。

您可以生成一个 js 文件来加载您的 js 和 css 文件,如下所示:

      // Generate js entrypoint for the app to be loaded using a script tag
      new HtmlWebpackPlugin({
        alwaysWriteToDisk: true,
        inject: false,
        chunks: ['cmsHelpers'],
        filename: 'cmsHelpers.js',
        minify: false,
        templateContent: ({ htmlWebpackPlugin }) => {
          return (
            dedent`
            "use strict";
            (function(m) {     
              var baseUrl = new URL(m.publicPath, document.currentScript.src);        
              m.js.forEach(src => {
                document.head.appendChild(Object.assign(document.createElement('script'), { src: new URL(src, baseUrl).toString() }));
              });
              m.css.forEach(href => {
                document.head.appendChild(Object.assign(document.createElement('link'), { rel: 'stylesheet', href: new URL(href, baseUrl).toString() }));
              });
            })(
          ` +
            JSON.stringify(htmlWebpackPlugin.files, null, 2) +
            ');'
          );
        },
      }),

然后在您的页面上加载该脚本。