[英]Import .js file as text and use it inside WebView injectedJavaScript in react-native expo
I have a file content.js
that includes some JavaScript code that I want to inject inside a WebView using injectedJavaScript
. 我有一个文件content.js
,包括我想使用的WebView内注入一些JavaScript代码injectedJavaScript
。
I tried: 我试过了:
fetch('./content.js').then((result) => {
result = result.text();
this.setState(previousState => (
{contentScript: result}
));
});
But it doesn't get the right file. 但是它没有得到正确的文件。
const contentScript = require('./content.js');
This works, but it evals the JavaScript straight away and I can't seem to find a way to convert it to string before it gets executed. 这可以工作,但是可以立即评估JavaScript,在执行之前,我似乎找不到找到将其转换为字符串的方法。
A solution is to just make copy the code of content.js
into a string, but that would be pretty annoying when I want to edit the code... 一种解决方案是只将content.js
的代码复制到字符串中,但是当我要编辑代码时,这会很烦人。
Does anyone know a better solution for this? 有谁知道更好的解决方案吗?
I still have no solution to this for almost a week. 我将近一个星期仍然没有解决办法。 :( :(
Since expo is using webpack you can customize it. 由于expo使用的是webpack,因此您可以对其进行自定义。 Webpack has a loaders section you might be interested in. And the loader you need is called raw-loader . 的WebPack有装载机 ,你可能会感兴趣的部分。而你所需要的程序叫原始装载机 。 So when you require some file, webpack runs this file against the chain of loaders it has in config. 因此,当您需要一些文件时,webpack会针对它在配置文件中的加载程序链来运行该文件。 And by default all .js
files are bundled into index.js
that gets executed when you run your app. 默认情况下,所有.js
文件都捆绑到index.js
,当您运行应用程序时,该文件将被执行。 Instead you need the content of the file that raw-loader
exactly does. 取而代之的是,您需要raw-loader
确切执行的文件内容。 It will insert something like 它将插入类似
module.contentScript = function() { return "console.log('Hello world!')"}
instead of: 代替:
module.contentScript = function() { console.log('Hello World'}}
So you need: 因此,您需要:
npm install raw-loader --save-dev
and inside your code: 在您的代码中:
require('raw-loader!./content.js');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.