Когда я нажимаю кнопку, я получаю следующую ошибку:
index.html: 12 Uncaught ReferenceError: приветствие не определено в HTMLButtonElement.onclick (index.html: 12)
Кажется, что код javascript, сгенерированный webpack или ts-loader, неверен. Любые идеи?
это мой index.ts
function greet(){
let p:HTMLElement=document.getElementById("p1")
p.innerHTML = "hello"
}это мой 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
/******/ });
/******/ }
/******/ };
/******/
/******/ // 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 = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/index.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./src/index.ts":
/*!**********************!*\
!*** ./src/index.ts ***!
\**********************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("function greet() {\r\n var p = document.getElementById(\"p1\");\r\n p.innerHTML = \"hello\";\r\n}\r\n\n\n//# sourceURL=webpack:///./src/index.ts?");
/***/ })
/******/ });это мой 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>Document</title>
</head>
<script src = "./bundle.js"></script>
<body>
<p id = "p1"></p>
<button onclick = "greet()">Greet </button>
</body>
</html>это мой tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}это мой webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode:"development"
};





вы должны предоставить функцию как библиотеку. Расширьте выходной объект в webpack.config.js:
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
libraryTarget: 'var',
library: 'MyLib'
}
Затем поместите функцию в статический класс с именем «библиотека» выше и экспортируйте его.
export static class MyLib {
public static greet() {
let p: HTMLElement = document.getElementById("p1")
p.innerHTML = "hello"
}
}
последний шаг - изменить событие в html-коде:
<button onclick = "MyLib.greet()">Greet </button>
Вы могли бы сделать что-то вроде ответа @A Loewer. Но проще всего сделать это,
function greet() {
let p: HTMLElement | null = document.getElementById("p1")
if (p)
p.innerHTML = "hello"
}
(<any>window).greet = greet;
Теперь ваша функция находится в глобальной области видимости.
Статические классы в машинописном тексте?