외부에서 웹 패킹된 코드를 호출합니다(HTML 스크립트 태그).
이와 같은 클래스(타자기본으로 작성)가 있으며 웹 팩과 함께 번들하여bundle.js.
export class EntryPoint {
static run() {
...
}
}
my index.html에 번들을 포함시키지만, 그 후 static 메서드도 호출하고 싶습니다.
<script src="build/bundle.js"></script>
<script>
window.onload = function() {
EntryPoint.run();
}
</script>
하지만, 그EntryPoint이 경우 정의되어 있지 않습니다.그럼 다른 스크립트에서 번들된 javascript를 어떻게 불러야 할까요?
웹 팩 번들을 라이브러리로 공개하려고 하는 것 같습니다.자체 변수 내에서 글로벌 컨텍스트에서 라이브러리를 공개하도록 웹 팩을 구성할 수 있습니다.EntryPoint.
저는 TypeScript를 모르기 때문에 예시는 플레인 JavaScript를 사용합니다.여기서 중요한 것은 웹 팩컨피규레이션파일입니다.특히,output섹션:
webpack.config.syslog
module.exports = {
entry: './index.js',
output: {
path: './lib',
filename: 'yourlib.js',
libraryTarget: 'var',
library: 'EntryPoint'
}
};
index.displaces를 표시합니다.
module.exports = {
run: function () {
console.log('run from library');
}
};
그러면 다음과 같이 라이브러리 메서드에 액세스할 수 있습니다.
<script src="lib/yourlib.js"></script>
<script>
window.onload = function () {
EntryPoint.run();
};
</script>
실제 코드와 함께 GIST를 확인합니다.
나는 이 일을 더 이상 하지 않고 해낼 수 있었다.webpack.config.js수정사항, 단순히 를 사용하여importmain/index.filename 파일에서 호출한 스테이트먼트:
import EntryPoint from './EntryPoint.js';
window.EntryPoint = EntryPoint;
참고로 여기 제 파일이 있습니다.
처음에 나는 같은 일을 하려고 했다.require단, 모듈래퍼를 에 할당했습니다.window.EntryPoint실제 수업과는 달리
제 상황에서는 번들된 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>
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>
웹 팩구성.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.displaces를 표시합니다.
<script src="dist/main.js"></script>
<script>
window.onload = function () {
rstate()=>{}
</script>
main.discloss.main.discloss.
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'
}
}
index.displaces를 표시합니다.
<script>
window.onload = function () {
EntryPoint.rstate()=>{}
</script>
main.discloss.main.discloss.
module.exports={
rstate=function(){
console.log("hi module")
}
}
3. AMD를 라이브러리로 사용 (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이 몇 할 수 있기를
index.timeout (번들되는 기능)>>
function EntryPoint() {
console.log('called from bundle');
}
module.exports = EntryPoint;
webpack.config.filename >>
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'var',
library: 'EntryPoint'
},
};
start.disc(번들함수가 호출되는 경우)>>
<!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>
App.ts:
namespace mytypescript.Pages {
export class Manage {
public Initialise() {
$("#btnNewActivity").click(() => {
alert("sdc'");
});
}
}
}
mypage.mypage:
<input class="button" type="button" id="btnNewActivity" value="Register New Activity" />
<script type="text/javascript">
var page = new mytypescript.Pages.Manage();
page.Initialise();
</script>
언급URL : https://stackoverflow.com/questions/34357489/calling-webpacked-code-from-outside-html-script-tag
'programing' 카테고리의 다른 글
| Ubuntu VPS에서 Spring Boot Actuator 응용 프로그램이 시작되지 않음 (0) | 2023.03.16 |
|---|---|
| 중복된 Mongo ObjectId가 두 개의 다른 컬렉션에서 생성되었을 가능성이 있습니까? (0) | 2023.03.16 |
| setInterval은 CPU를 많이 사용합니까? (0) | 2023.03.16 |
| 리액트 네이티브 플렉스 박스 포함 전폭 버튼 (0) | 2023.03.16 |
| JsonNode 개체를 맵으로 변환 (0) | 2023.03.16 |
