외부에서 웹팩 코드 호출 (HTML 스크립트 태그)


130

이 클래스 (typescript로 작성)가 있고 webpack과 함께 번들로 묶었다고 가정하십시오 bundle.js.

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

내 index.html에 번들을 포함시킬 것이지만 정적 메소드를 호출하고 싶습니다.

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

그러나이 EntryPoint경우에는 정의되지 않습니다. 그러면 다른 스크립트에서 번들로 제공되는 자바 스크립트를 어떻게 호출합니까?

추가 : Webpack 구성 파일 .


웹팩 구성을 추가하십시오. 나는 var EntryPoint = require('EntryPoint')당신의 onload방법 에서 줄을 따라 뭔가가 빠졌다고 생각합니다 .
— Martin Vseticka

2
@MartinVseticka 구성을 추가했습니다. 실제로 require필요할 수도 있지만 아래의 가져 오기와 같은 내용 이 있습니다 require is not defined. 내가하려고하는 것은 일반 자바 스크립트에서 번들 콘텐츠를 사용하는 것입니다. 사용하기 위해 다시 프레임 워크가 필요하지 require않습니까? 그러나 나는 그것을 피하려고 노력하고 있습니다. 이해가 되길 바랍니다.
— Raven

답변:


147

웹팩 번들을 라이브러리 로 노출하려는 것 같습니다 . 와 같은 전역 변수에서 라이브러리를 노출하도록 웹팩을 구성 할 수 있습니다 EntryPoint.

TypeScript를 모르므로 예제에서 일반 JavaScript를 대신 사용합니다. 그러나 여기서 중요한 부분은 웹팩 구성 파일, 특히 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>

실제 코드로 요점 을 확인하십시오 .


20
여러 개의 진입 점이 있으므로 출력 섹션에서 대신 만들었습니다 library: ["GlobalAccess", "[name]"],. 그런 다음 var를 각 진입 점에 대한 멤버가있는 객체로 만듭니다. GlobalAccess.EntryPointFoo, GlobalAccess.EntryPointBar 등
— John Hatton

3
이것은 nam run builddev env를 사용하여 작동하지만 작동 하지 않습니다 webpack-dev-server. 내 보낸 EntryPoint는 빈 개체입니다. 어떤 아이디어?
— nkint

1
항목 : {page1 : [ 'module1.js', 'module2.js'], page2 : 'module3.js'} @JohnHatton 제안이 작동하지 않는 것 같습니다. page1.module2에 액세스 할 수 있지만 page1.module1에는 액세스 할 수 없습니다. 마지막 하나를 취하는 것 같습니다.
— sheamus

1
단계, 구성 변경, 다시 빌드했지만 여전히 포착되지 않음 ReferenceError : EntryPoint가 정의되지 않았습니다.
— user889030

2
index.js를 다음 export function run() {}과 같이 변경하여 babel + webpack v3.10.0에서 작동하는 유사한 예제를 얻었습니다.module.exports = ...
— dworvos

55

나는 main / index.js 파일에서 호출 webpack.config.js한 import명령문을 사용하여 추가 수정 없이이 작업을 수행 할 수있었습니다 .

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

여기에 이미지 설명을 입력하십시오

참고로 여기 내 weback.config.js파일이 있습니다.

처음에는을 사용하여 동일한 작업을 시도했지만 실제 클래스와 반대로 require모듈 래퍼를 할당했습니다 window.EntryPoint.


3
es6 없이이 작업을 수행 할 수 있습니까? 그렇지 않으면 나는 얻는다 Uncaught SyntaxError: Unexpected token import. 또는 index.js번들로 제공됩니까 (입력 지점으로 보지만 확실하지는 않습니다)?
— Raven

예, index.js도 함께 제공됩니다. 여기에 수입 명세서가 포함되어 있습니다
— Matt

3
글쎄, 번들에 속하지 않은 스크립트에서 번들로 제공되는 것에 액세스하려고합니다. 번들이 라이브러리 인 것처럼 외부에서 메소드에 액세스하려고합니다. 가능합니까?
— Raven

4
이 솔루션은 정말 간단하며 문제가 발생하자마자 생각하지 않아 부끄러워합니다.
— cav_dan

1
나는이 문제에 몇 시간 동안 붙어있었습니다. 스크립트를 내 번들로 옮길 예정이지만 더 많은 문제가 발생했을 것입니다. 간단한 답변 감사합니다 !!
— Stephen Agwu

14

내 상황에서는 번들 스크립트를 만들 때 창에 함수를 작성하여 다른 스크립트의 번들 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>

나는 바벨을 사용할 수 없었기 때문에 이것이 나를 위해 일했다.


이것은 매우 깔끔한 솔루션입니다.
— Teoman shipahi

1

나는 비슷한 과제를 겪고 있었고, 여정 내에서 여러 페이지에 대한 번들을 만들고 싶었고 각 페이지마다 코드에 대한 고유 한 진입 점이 있고 각 페이지마다 별도의 번들이 없어지기를 원했습니다.

여기 내 접근 방식은 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>

0

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>

main.js

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

2. 사용 바

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>
  window.onload = function () {
  EntryPoint.rstate()=>{}
</script>

main.js

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

3. AMD를 우리가 사용하는 라이브러리로 사용

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

-4

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>
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.