Import .js file as text and use it inside WebView injectedJavaScript in react-native expo

旧城冷巷雨未停 提交于 2020-03-23 12:32:29

问题


I have a file content.js that includes some JavaScript code that I want to inject inside a WebView using 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.

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


回答1:


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!')"}

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


来源:https://stackoverflow.com/questions/57170036/import-js-file-as-text-and-use-it-inside-webview-injectedjavascript-in-react-na

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!