从外部调用 webpack 代码(HTML 脚本标记)

假设我有这样的类(用类型脚本编写) ,并将其与 webpack 绑定到 bundle.js中。

export class EntryPoint {
static run() {
...
}
}

在 index.html 中,我将包含这个 bundle,但是之后我还想调用这个静态方法。

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

但是,在这种情况下,EntryPoint是未定义的。那么我如何从另一个脚本调用绑定的 javascript 呢?

新增 : Webpack 配置文件

68560 次浏览

通过简单地使用我在 main/index.js 文件中调用的 import语句,我设法在没有进一步修改 webpack.config.js的情况下实现了这个功能:

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

enter image description here

作为参考,这是我的 weback.config.js文件。

最初,我尝试使用 require完成同样的任务,但是它将模块包装器分配给 window.EntryPoint,而不是实际的类。

您似乎希望将 webpack 包作为 图书馆公开。您可以将 webpack 配置为在自己的变量(如 EntryPoint)中的全局上下文中公开库。

我不知道 TypeScript,所以这个例子使用了普通的 JavaScript 代替。但是这里的重要部分是 webpack 配置文件,特别是 output部分:

Webpack.config.js

module.exports = {
entry: './index.js',
output: {
path: './lib',
filename: 'yourlib.js',
libraryTarget: 'var',
library: 'EntryPoint'
}
};

Index.js

module.exports = {
run: function () {
console.log('run from library');
}
};

然后你就可以像你期望的那样访问你的库方法:

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

用实际代码检查 大意

应用程序:

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>

在我的情况下,我可以通过在创建函数时将函数写到窗口中,从绑定的 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>

我不能使用巴别塔,所以这对我很有用。

我也遇到过类似的挑战,我想为一个旅程中的多个页面创建一个 bundle,并希望每个页面都有自己的代码入口点,而不是为每个页面单独创建一个 bundle。

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

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>

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'
}
}

Html

<script src="dist/main.js"></script>
<script>
window.onload = function () {
rstate()=>{}
</script>

主要的

export default function rstate(){
console.log("i called from html")
}

2. 使用 VAR

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

Html

<script>
window.onload = function () {
EntryPoint.rstate()=>{}
</script>

主要的

module.exports={
rstate=function(){
console.log("hi module")
}
}

3. 使用 AMD 作为库,我们使用 like (对于那些想要使用 lib 的人)

define(['jquery', './aux-lib.js'], function ($) { ..(1).. });

到目前为止,许多答案都是有效的,只需要说明 Webpack 在声明库之后才能识别它。 您应该在创建库之后立即使用 npm run build, 在继续使用 npm start之前。

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

也许这是我的一些冒名顶替症候群,但我认为“真正的”程序员会对我的回答感到畏缩。不管怎样,我发现这个解决方案最适合我实际利用业余爱好项目的时间:

更改 JS 函数声明:

function renderValue(value) {

致:

global.renderValue = function(value) {

当然,您会希望像处理任何文件一样处理 require('path/to/your_custom_js')

我在这里找到了答案: Https://www.fastruby.io/blog/rails/webpack/from-sprockets-to-webpacker.html

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

Js (要绑定的函数) > >

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


module.exports = EntryPoint;

Webpack.config.js > >

const path = require('path');


module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'var',
library: 'EntryPoint'
},
};

.html (其中调用了绑定的函数) > >

<!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>