簡體   English   中英

使用 bundle.js 中的函數時出現 HTML 錯誤

[英]HTML error using functions from bundle.js

我使用 webpack 創建了一個 bundle.js 文件來組織我所有的 javascript 代碼。 我期待在我的 html 文件中使用它,但在使用 function 時遇到了麻煩。 當我嘗試調用 function index.html:9 Uncaught TypeError: App.testButton is not a function at setup總是返回錯誤。

我的印象是,如果我用指定的庫 output 配置 webpack,我將能夠通過指定的庫名稱訪問這些函數。

我究竟做錯了什么?

應用程序.js

import testButton from './testButton.js';

console.log("I'm the entry point");
testButton();

testButton.js

function testButton()
{
    console.log("Test Button");
};

export default testButton;

索引.html

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="dist/bundle.js"></script>
  <script>
  function setup()
    {
        console.log("Initializing a webpage");
        App.testButton()
    }
  </script>
</head>
<body onload="setup();">
</body>
</html>

webpack.config.js

const path = require('path');

module.exports = {
  entry: './app.js',
  mode: 'development',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    libraryTarget: 'var',
    library: 'App'
  },
};

我發現這對我有用。 我需要修改 App.js 以包含 babel,這樣我就可以使用 ES5,它允許我使用 require 來填充 module.exports。

應用程序.js

require('babel-register')({
    presets: ['env']
});

module.exports = {
    testButton: require('./testButton.js'),
    testButton2: require('./testButton2.js')
};

testButton.js

export function testButton()
{
    console.log("Test Button");
};

testButton2.js

export function testButton()
{
    console.log("Test Button 2");
};

索引.html

function setup()
{
    App.testButton.testButton();
    App.testButton2.testButton();
}
</script>

Output 在控制台測試按鈕測試按鈕 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM