[英]How to use function from NPM library in html.eex template
Using Phoenix 1.4 with webpack, I added "findandreplacedomtext": "^0.4.6"
to my package.json file and installed the library. 在Web Pack上使用Phoenix 1.4,我在package.json文件中添加了"findandreplacedomtext": "^0.4.6"
并安装了库。
Now in app.js I have import findAndReplaceDOMText from 'findandreplacedomtext';
现在在app.js中,我import findAndReplaceDOMText from 'findandreplacedomtext';
and that allows me to use the library, but it only works within the app.js file . 并允许我使用该库, 但它仅在app.js文件中有效 。 I want to be able to use the library in my view templates but whenever I try to use it in a template, I get an error in the console Uncaught ReferenceError: findAndReplaceDOMText is not defined
. 我希望能够在视图模板中使用该库,但是每当尝试在模板中使用该库时,都会在控制台中收到错误信息Uncaught ReferenceError: findAndReplaceDOMText is not defined
。
This is what the code looks like inside of my template: 这是我的模板中的代码:
<div id="container">
This is a test.
</div>
<script>
findAndReplaceDOMText(document.getElementById('container'), {
find: 'test',
wrap: 'mark'
});
</script>
That throws an error in the console. 这会在控制台中引发错误。 But if I put the same javascript code in app.js below the library's import statement it works. 但是,如果我在库的import语句下面将相同的javascript代码放在app.js中,则它可以工作。 How can I use the library inside of my view template and outside of app.js? 如何在视图模板内部和app.js外部使用库?
错误出在您的js中,您正在通过ID“容器”选择一个元素,但这是一个类,因此应为:
findAndReplaceDOMText(document.getElementsByClassName('container')
At the top of webpack.config.js I put const webpack = require('webpack');
在webpack.config.js的顶部,我将const webpack = require('webpack');
so that in the plugins list I could put new webpack.ProvidePlugin({findAndReplaceDOMText: "findandreplacedomtext"})
. 这样我就可以在插件列表中放入new webpack.ProvidePlugin({findAndReplaceDOMText: "findandreplacedomtext"})
。 This made it so that I could remove the import statement for the library from app.js. 这样可以使我可以从app.js中删除该库的import语句。
Then, in app.js I put window.findAndReplaceDOMText = findAndReplaceDOMText;
然后,在app.js中,我将window.findAndReplaceDOMText = findAndReplaceDOMText;
in order to expose the module outside of app.js. 为了将模块公开到app.js之外。
Finally, in my template, I had to wrap the function in a content loaded event in order to make sure I wasn't invoking the function before it was loaded. 最后,在我的模板中,我必须将函数包装在一个内容加载事件中,以确保在加载函数之前不调用该函数。
<script>
document.addEventListener("DOMContentLoaded", function(event) {
findAndReplaceDOMText(document.getElementById('container'), {
find: 'test',
wrap: 'mark'
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.