javascript - 使用 WebPack 时找不到函数

标签 javascript webpack

在 HTML 页面上我有以下内容:

<button onclick="openAlert()">Open</button>

还有一个带有openAlert函数的scripts.js文件:

function openAlert() {
  alert("Alert is opened");
}

当我单击该按钮时,警报会按预期打开。

然后我使用 Webpack 使用 webpack.config 缩小 scripts.js 文件:

const webpack = require('webpack');

var UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {

  resolve: {
    extensions: ['.js'],
  },

  entry: {
    'scripts.min': './scripts/scripts.js',
  },  

  output: {
    path:  __dirname + '/dist',
    filename: '[name].js'
  },

  optimization: {
    minimizer: [    
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: false
      })
    ]
  },

};

scripts.min.js 文件已创建并正确加载到页面上。

但是当我点击按钮时出现以下错误:

ReferenceError: Can't find variable openAlert

我做错了什么?

生成的scripts.min.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, { enumerable: true, get: getter });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/        }
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave like require
/******/    __webpack_require__.t = function(value, mode) {
/******/        if(mode & 1) value = __webpack_require__(value);
/******/        if(mode & 8) return value;
/******/        if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/        var ns = Object.create(null);
/******/        __webpack_require__.r(ns);
/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/        return ns;
/******/    };
/******/
/******/    // 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 = "./wwwroot/scripts/scripts.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./wwwroot/scripts/scripts.js":
/*!************************************!*\
  !*** ./wwwroot/scripts/scripts.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports) {

eval("function openAlert() {\n  alert(\"Alert is opened\");\n}\n\n//# sourceURL=webpack:///./wwwroot/scripts/scripts.js?");

/***/ })

/******/ }); 

最佳答案

这是因为 webpack 在自己的范围内创建所有变量。

你可以看到

(function(modules) { 

 ...code

}); // end of scope 

如果你在 window 作用域中添加你的函数,你可以离开作用域

示例 window.openAlert = function(){...}

但这是不好的做法

或者你需要在html文件中导入这个函数然后你需要添加HTML loader在网络包中

关于javascript - 使用 WebPack 时找不到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56805556/

相关文章:

javascript - 渲染远程 json

javascript - 奥里利亚网页包 : how to load images

javascript - 为什么 JSX 不保存为 const 渲染

javascript - 在 Javascript 中将函数结果传递给另一个函数变量

javascript - 任何写出 javascript 的高级语言?

webpack - Watchpack 错误(初始扫描): Error: EACCES: permission denied, lstat '/mnt/c/DumpStack.log.tmp'

javascript - 节点和浏览器在 package.json 中的不同主要入口点

javascript - 使用 JS 在单击时更改 DIV z-index 并返回原始值

javascript - Webpack 将故事书添加到 create-react-app 时出错

node.js - 在 Firebase 托管上安装 NPM 依赖项