Javascript 从外部调用网页包代码(HTML脚本标记)

Javascript 从外部调用网页包代码(HTML脚本标记),javascript,html,typescript,webpack,Javascript,Html,Typescript,Webpack,假设我有这样的类(用typescript编写),我将它与webpack绑定到bundle.js export class EntryPoint { static run() { ... } } 在我的index.html中,我将包含这个包,但是我还想调用这个静态方法 <script src="build/bundle.js"></script> <script> window.onload = function() {

假设我有这样的类(用typescript编写),我将它与webpack绑定到
bundle.js

export class EntryPoint {
    static run() {
        ...
    }
}
在我的index.html中,我将包含这个包,但是我还想调用这个静态方法

<script src="build/bundle.js"></script>
<script>
    window.onload = function() {
        EntryPoint.run();
    }
</script>

window.onload=函数(){
EntryPoint.run();
}
但是,在这种情况下,
入口点
未定义。那么,如何从另一个脚本调用绑定的javascript呢


添加了:。

我只需使用我在主/index.js文件中调用的
import
语句,就可以在不做任何进一步的
webpack.config.js
修改的情况下实现这一点:

import EntryPoint from './EntryPoint.js';
window.EntryPoint = EntryPoint;

作为参考,这是我的档案


最初,我尝试使用
require
实现相同的功能,但是它将模块包装器分配给了
window.EntryPoint
,而不是实际的类。

似乎您希望将webpack捆绑包作为一个组件公开。您可以将webpack配置为在自己的变量(如
EntryPoint
)内的全局上下文中公开库

我不知道TypeScript,所以示例使用纯JavaScript。但这里最重要的部分是webpack配置文件,特别是
输出部分:

webpack.config.js index.js 然后,您将能够像预期的那样访问库方法:

<script src="lib/yourlib.js"></script>
<script>
  window.onload = function () {
    EntryPoint.run();
  };
</script>

window.onload=函数(){
EntryPoint.run();
};
用实际代码检查。App.ts:

namespace mytypescript.Pages {

        export class Manage {

     public Initialise() {
     $("#btnNewActivity").click(() => {
                    alert("sdc'");
                });
        }
    }
}
mypage.html:

 <input class="button" type="button" id="btnNewActivity" value="Register New Activity" />

 <script type="text/javascript">
    var page = new mytypescript.Pages.Manage();
    page.Initialise();
</script>

var page=new mytypescript.Pages.Manage();
page.Initialise();

在我的情况下,通过在创建窗口时将函数写入窗口,我可以从另一个脚本的捆绑JavaScript中调用函数

// In the bundled script:
function foo() {
    var modal = document.createElement('div');
}
// Bind to the window
window.foo = foo;
// Then, in the other script where I want to reference the bundled function I just call it as a normal function
<button onClick="window.foo()">Click Me</button>
//在捆绑脚本中:
函数foo(){
var modal=document.createElement('div');
}
//绑在窗户上
window.foo=foo;
//然后,在另一个脚本中,我想引用绑定函数,我只是将其作为普通函数调用
点击我

我无法使用Babel,所以这对我来说很有效。

我有一个类似的挑战,我想为一次旅程中的多个页面创建一个捆绑包,并希望每个页面都有自己的代码入口点,并且每个页面都没有单独的捆绑包

以下是我的方法,它与Kurt Williams非常相似,但从一个稍微不同的角度来看,也没有更改网页包配置:

JourneyMaster.js

import { getViewData } from './modules/common';
import { VIEW_DATA_API_URL } from './modules/constants';
import { createLandingPage, createAnotherPage } from './modules/components/pageBuilder';

window.landingPageInit = () => {
    getViewData(VIEW_DATA_API_URL).then(viewData => {
        createLandingPage(viewData);
    });
};

window.anotherPageInit = () => {
    getViewData(VIEW_DATA_API_URL).then(viewData => {
        createAnotherPage(viewData);
    });
};

// I appreciate the above could be one liners,
// but readable at a glance is important to me
然后,我在
html
页面末尾调用这些方法的示例:

<script src="/js/JourneyMaster.js"></script>
<script>window.landingPageInit();</script>

window.landingPageInit();

WEBPACK.CONFIG.JS

1.使用UMD

module.exports={
            mode:'development',
            entry:'./yourentry.js',
            output:{
                path:path.resolve(__dirname,"dist"),
                filename:'main.js',
                publicPath:'/dist/',
                libraryTarget:'umd', 
                library:'rstate',
                umdNamedDefine: true,
                libraryExport: 'default' 
            }
    }
index.html

<script src="dist/main.js"></script>
<script>
  window.onload = function () {
  rstate()=>{}
</script>
<script>
  window.onload = function () {
  EntryPoint.rstate()=>{}
</script>
2.使用VAR

module.exports={
            mode:'development',
            entry:'./yourentry.js',
            output:{
                path:path.resolve(__dirname,"dist"),
                filename:'main.js',
                publicPath:'/dist/',
                libraryTarget:'var', 
                library: 'EntryPoint'
            }
    }
index.html

<script src="dist/main.js"></script>
<script>
  window.onload = function () {
  rstate()=>{}
</script>
<script>
  window.onload = function () {
  EntryPoint.rstate()=>{}
</script>
3.使用AMD作为库,我们使用like(对于那些想制作库的人)


到目前为止,许多答案都是有效的,只需要澄清一点,即Webpack不会识别该库,直到它在声明后构建。 您应该在创建库之后立即使用
npm run build
, 在继续使用
npm之前,请启动


至少对我来说是这样的,只使用网页包。

也许这是我的冒名顶替综合症,但我认为“真正的”程序员会对我的答案感到畏缩。不管怎样,我发现这个解决方案最适合我在业余爱好项目中务实地对待时间:

从以下位置更改JS函数声明:

function renderValue(value) {
致:

当然,您需要
require('path/to/your_custom_js')
,就像您需要任何文件一样

我在这里找到了答案:

我花了很长时间才弄明白,因为公认的答案对我不起作用。只需确保函数名与配置中的库相同,并与指定的配置捆绑在一起--
npx webpack--config webpack.config.js--mode=development
--希望这样可以节省人们几个小时的时间

index.js(要捆绑的功能)>>

function EntryPoint() {
    console.log('called from bundle');
}

module.exports = EntryPoint;
const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
        libraryTarget: 'var',
        library: 'EntryPoint'
    },
};
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Azure SDK Storage Example</title>
    <script type="text/javascript" src="./dist/main.js"></script>
  </head>
  <body>
      <h1>Azure SDK Storage Example</h1>
  </body>
</html>

<script>
 EntryPoint();
</script>
webpack.config.js>>

function EntryPoint() {
    console.log('called from bundle');
}

module.exports = EntryPoint;
const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
        libraryTarget: 'var',
        library: 'EntryPoint'
    },
};
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Azure SDK Storage Example</title>
    <script type="text/javascript" src="./dist/main.js"></script>
  </head>
  <body>
      <h1>Azure SDK Storage Example</h1>
  </body>
</html>

<script>
 EntryPoint();
</script>
start.html(调用捆绑函数的地方)>>

function EntryPoint() {
    console.log('called from bundle');
}

module.exports = EntryPoint;
const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist'),
        libraryTarget: 'var',
        library: 'EntryPoint'
    },
};
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Azure SDK Storage Example</title>
    <script type="text/javascript" src="./dist/main.js"></script>
  </head>
  <body>
      <h1>Azure SDK Storage Example</h1>
  </body>
</html>

<script>
 EntryPoint();
</script>

Azure SDK存储示例
Azure SDK存储示例
入口点();

请添加您的网页配置。我相信您的
onload
方法中缺少了与
var EntryPoint=require('EntryPoint')
类似的内容。@MartinVseticka我已经添加了配置。实际上,像
require
这样的东西可能是必需的,但与下面的import相同,它表示
require没有定义。我想做的是使用普通javascript中的捆绑内容,我不需要再使用一些框架来使用
require
?但我正试图避免这种情况。希望这是有意义的。没有es6的情况下有机会这样做吗?否则我会得到
未捕获的语法错误:意外的令牌导入
。或者你的
index.js
也是捆绑的(我确实把它看作是入口点,但不确定)?是的,index.js也是捆绑的-这就是我包含导入语句的地方。你看,我正试图访问从不属于捆绑的脚本捆绑的东西。就像包是一个库一样,我会尝试从外部访问它的方法。这可能吗?这个解决方案真的很简单,我为自己一出现问题就不去想而感到羞愧。我已经在这个问题上纠缠了好几个小时了。我只是想把脚本放到我的包里,但那会引起更多的问题。谢谢你简单的回答!!我们有多个入口点,因此在输出部分,我将其改为
库:[“GlobalAccess”、“[name]”、
。然后使var成为一个对象,每个入口点都有成员:GlobalAccess.EntryPointFoo、GlobalAccess.EntryPointBar等。这适用于
namrunbuild
,但不适用于使用
webpack dev server
的dev env。我导出的入口点是一个空的o