将.js文件作为文本导入并在react-native博览会中的WebView InjectionJavaScript内部使用

问题描述:

我有一个文件content.js,其中包含一些我想使用injectedJavaScript注入到WebView中的JavaScript代码.

I have a file content.js that includes some JavaScript code that I want to inject inside a WebView using injectedJavaScript.

我尝试过:

    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');

这有效,但是可以立即评估JavaScript,在执行之前,我似乎找不到找到将其转换为字符串的方法.

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.

一种解决方案是将content.js的代码复制到字符串中,但是当我要编辑代码时,这会很烦人.

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...

有人知道对此有更好的解决方案吗?
我将近一个星期仍然没有解决办法. :(

Does anyone know a better solution for this?
I still have no solution to this for almost a week. :(

由于expo使用加载器部分.您需要的加载器称为原始加载器.因此,当您需要一些文件时,webpack会针对它在配置文件中的加载程序链来运行该文件.默认情况下,所有.js文件都捆绑到index.js中,而这些文件在您运行应用程序时会执行.相反,您需要raw-loader确切执行的文件内容.它将插入类似

Since expo is using webpack you can customize it. Webpack has a loaders section you might be interested in. And the loader you need is called raw-loader. So when you require some file, webpack runs this file against the chain of loaders it has in config. And by default all .js files are bundled into index.js that gets executed when you run your app. Instead you need the content of the file that raw-loader exactly does. It will insert something like

module.contentScript = function() { return "console.log('Hello world!')"}

代替:

module.contentScript = function() { console.log('Hello World'}}

所以您需要:

npm install raw-loader --save-dev

并在您的代码中:

require('raw-loader!./content.js');