如何使用 webpack-dev-server 获得简单的 Webpack 捆绑包和 运行

How to get simple Webpack bundle up and running using webpack-dev-server

我只是触及了使用 webpack、webpack-dev-server 和热模块重新加载构建我的开发环境的皮毛。我希望最终能够将 React 组件添加到主要静态站点(以便我获得可抓取 html 的 SEO 优势。我决定不使用 Gulp 或 G运行t,相反,我将单独使用 npm 脚本来 运行 shell 命令进行开发、测试、构建和发布。

回到本题的title/topic。我无法让浏览器读取由 webpack 生成的 bundle.js 文件。我已经将我的图书馆归结为最简单的 index.htmlindex.js,您可以在下面看到。

控制台的错误输出是:

Uncaught ReferenceError: handleClick is not defined
at HTMLButtonElement.onclick ((index):7)

发出的 bundle.js 文件必须是错误所在:

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // 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
/******/            });
/******/        }
/******/    };
/******/
/******/    // 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 = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

const handleClick = () => {
  document.getElementById("demo").innerHTML = "Hello World!";
};

/***/ })
/******/ ]);

我的 index.html 文件:

<html>
<body>

<p id="demo">Simple JS demo</p>

<script src="bundle.js"></script>
<button type="button" onclick='handleClick()'>Click Me!</button>

</body>
</html>

我的 index.js 文件:

const handleClick = () => {
  document.getElementById("demo").innerHTML = "Hello World!"
}

我的 webpack.config.js 文件:

const config = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: '/home/andrew/code/my-site/public',
  },
  module: {
    rules: [
      {
        test: /\.(js)$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader',
        }
      }
    ]
  }
};

module.exports = config;

我的npm start脚本:

  "scripts": {
    "start": "webpack-dev-server --content-base public/"
  }

我全局安装了 webpack,因此我可以使用命令 webpackpublic/ 文件夹中生成 bundle.js 文件,尽管 npm start 发出 bundle.js 文件。

一定是我犯了一些简单的错误。

来自@Marek Takac 的解决方案: 这里的错误是 handleClick() 函数的作用域不是全局的。这可以通过从 index.js 文件

中导出模块来解决
module.exports = {
  handleClick: handleClick
}

并使用 webpack 的 output.library and output.libraryTarget 选项来定义一个全局变量。

另见 webpack 的 exports-loader

你的 webpack 包似乎没问题。问题出在您的代码中。 handleClick 函数未定义,因为您是从全局环境中调用它的。您基本上尝试调用 window.hanldeClick 但您在完全不同的范围内定义了 handleClick 函数。 Webpack 将函数放入单独的闭包中,以防止污染您的全局环境。我建议您阅读一些 webpack/react 教程、指南和文档。但是,如果您只想测试您的设置是否正常工作,请从 index.js 文件中将某些内容记录到控制台。或者,我认为如果将 const handleClick 更改为 window.handleClick,您的代码应该可以工作(尽管我从未尝试过这样的事情)。