向 Angular 库添加脚本

22

我正在尝试将我的Angular 6应用程序的一些组件导出到一个库中。不幸的是,我需要使用WebToolkit来连接其他人构建的专有服务,该服务仅作为纯JavaScript文件提供。反过来,该文件还需要jQueryrequire.js

没有库,我通过在.angular-cli.json下添加这些js文件到"scripts"中解决了这个问题。

{
 ...,
 scripts: [
  "node_modules/jquery/dist/jquery.js",
  "node_modules/require/require.js",
  "path/to/my/magic/library.js"
 ],
 ...
}

现在我正在构建我的Angular库,我希望将这些脚本构建到我的库代码中,以便我的客户仍然可以通过执行只有一个npm-install和在他们的.module.ts文件中导入它的简单方式来使用。

使用Angular-CLI 6有可能实现吗?或者你有其他建议可以帮助我实现库的简单安装吗?


3
你能解决这个问题吗? - Oren Hizkiya
1
很遗憾,目前似乎还没有实现这个的方法。 - PeterO
2
谢谢@PeterO - 希望很快能找到解决方案。 - Oren Hizkiya
这不是最漂亮的,但你可以使用ngx-script-loader。你可以将多个脚本合并成一个脚本并分发它们。 - inorganik
请问您能否分享一个在 https://stackblitz.com/ 上演示问题的示例? - abdulrahman alaa
你是否考虑过创建一个Angular库,作为这个外部JS库的包装器?https://indepth.dev/posts/1193/create-your-standalone-angular-library-in-10-minutes - vanderdill
2个回答

1
   Provide the reference of your external JS in your angular. json file of main angular project in a script tag and provide the path of your package from your libraries node_modules folder like this. So now you have created the NPM package from your library and you are going to use it in different project

    **Add externaljs file**
    **Step 1**
    Take a file in the assets folder and set any name. Like as custom.js 
    
    function getToday() {
    alert(new Date().toLocaleDateString());
}

function greetings(name) {
    alert(`wellcome ${name}`);
}


    **Step 2**
    Now add the customjs file reference in the angular.json scripts section array list. Like as below

    
"src/assets/custom.js"

    **Step 3**
    Now add the functions reference in a component file. I am using the app component.ts

    //external js function declaration
declare function getToday(): any;
declare function greetings(name: any): any;
ngOnInit(): void {
    // call the externaljs functions
    getToday(); // without param
    greetings('rohol'); // with param
}

 

0

也许这不是最干净的方法,但您可以通过以下方式实现:

let scriptTap = document.createElement('script');
scriptTag.src = '<route to your scripts>';
document.body.appendChild(scriptTag);

集成的最佳方式是从ng new project-name -create-application=false创建库,然后使用ng g library name-of-library添加库。

这样,您就可以拥有一个干净的项目来开发您的库。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接