问题描述
我想将react-native-web应用程序嵌入到现有网站中,目前正在寻找实现此目的的选项。
该应用程序应该是一个非常简单的调查表,需要将其嵌入到由Elementor创建的网站中。我的想法是使用Elementor HTML widget并以某种方式插入我的应用程序,但不幸的是我无法弄清楚该怎么做。
我在开发React Native(RN)应用方面有一些经验,但是我对Web开发非常陌生,因此我认为使用RN和react-native-web库会更容易。
到目前为止,我已经使用npx react-native init WebApp
创建了一个RN项目,复制了 App.js , index.js 和 package.json来自react-native-web CodeSandbox template的文件,删除了 node_modules 文件夹,然后运行npm install
。然后,我能够使用 package.json 中的脚本启动并构建此示例Web应用程序。
现在我的问题是,如何使用 build 目录中的输出并将其嵌入到html标记中?
我还尝试将webpack与react-native-web docs的配置结合使用,以捆绑该应用程序,但在修复最后一个错误后,我总是会遇到新的错误。是否可以将RN应用程序捆绑到一个JS文件中,然后将其插入网站?
期待任何建议!
马可
解决方法
我通过使用以下webpack配置解决了该问题。创建的bundle.web.js的内容被放入脚本标签(<script>...</script>
)中。可以将其嵌入到HTML小部件中。
// web/webpack.config.js
const path = require('path');
const webpack = require('webpack');
const appDirectory = path.resolve(__dirname,'');
// This is needed for webpack to compile JavaScript.
// Many OSS React Native packages are not compiled to ES5 before being
// published. If you depend on uncompiled packages they may cause webpack build
// errors. To fix this webpack can be configured to compile to the necessary
// `node_module`.
const babelLoaderConfiguration = {
test: /\.js$/,// Add every directory that needs to be compiled by Babel during the build.
include: [
path.resolve(appDirectory,'index.web.js'),path.resolve(appDirectory,'src'),'node_modules/react-native-uncompiled'),],use: {
loader: 'babel-loader',options: {
cacheDirectory: true,// The 'metro-react-native-babel-preset' preset is recommended to match React Native's packager
presets: ['module:metro-react-native-babel-preset'],// Re-write paths to import only the modules needed by the app
plugins: ['react-native-web'],},};
// This is needed for webpack to import static images in JavaScript files.
const imageLoaderConfiguration = {
test: /\.(gif|jpe?g|png|svg)$/,use: {
loader: 'url-loader',options: {
name: '[name].[ext]',};
module.exports = {
entry: [
// load any web API polyfills
// path.resolve(appDirectory,'polyfills-web.js'),// your web-specific entry file
path.resolve(appDirectory,'src/index.js'),// configures where the build ends up
output: {
filename: 'bundle.web.js',path: path.resolve(appDirectory,'dist'),// ...the rest of your config
module: {
rules: [babelLoaderConfiguration,imageLoaderConfiguration],resolve: {
// This will only alias the exact import "react-native"
alias: {
'react-native$': 'react-native-web',// If you're working on a multi-platform React Native app,web-specific
// module implementations should be written in files using the extension
// `.web.js`.
extensions: ['.web.js','.js'],};