【问题标题】:HTML error using functions from bundle.js使用 bundle.js 中的函数的 HTML 错误
【发布时间】:2020-05-02 03:03:42
【问题描述】:

我使用 webpack 创建了一个 bundle.js 文件来组织我所有的 javascript 代码。我期待在我的 html 文件中使用它,但在使用该函数时遇到了麻烦。当我尝试调用函数index.html:9 Uncaught TypeError: App.testButton is not a function at setup 时总是返回错误。

我的印象是,如果我使用指定的库输出配置 webpack,我将能够通过指定的库名称访问函数。

我做错了什么?

App.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;

index.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'
  },
};

【问题讨论】:

    标签: javascript html webpack bundle


    【解决方案1】:

    我发现这对我有用。我需要修改 App.js 以包含 babel,这样我就可以使用 ES5,它允许我使用 require 来填充 module.exports。

    App.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");
    };
    

    index.html

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

    控制台输出 测试按钮 测试按钮 2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      相关资源
      最近更新 更多