我对前端很陌生——试图在 React 上实现客户端。添加“react-native”依赖并运行
webpack
后,我收到以下错误:
ERROR in ./node_modules/react-native/index.js 13:7
Module parse failed: Unexpected token (13:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 'use strict';
|
> import typeof AccessibilityInfo from './Libraries/Components/AccessibilityInfo/AccessibilityInfo';
| import typeof ActivityIndicator from './Libraries/Components/ActivityIndicator/ActivityIndicator';
| import typeof Button from './Libraries/Components/Button';
@ ./node_modules/@react-navigation/native/lib/module/useBackButton.js 2:0-43 5:25-36
@ ./node_modules/@react-navigation/native/lib/module/index.js
@ ./src/main/js/app.js
我在 package.json 中有以下依赖项:
"dependencies": {
"@react-native-community/masked-view": "^0.1.7",
"@react-navigation/native": "^5.1.4",
"@react-navigation/stack": "^5.2.9",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-native": "^0.62.1",
"react-native-gesture-handler": "^1.6.1",
"react-native-reanimated": "^1.7.1",
"react-native-safe-area-context": "^0.7.3",
"react-native-screens": "^2.4.0",
"rest": "^2.0.0"
},
"scripts": {
"watch": "webpack --watch -d"
},
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/preset-env": "^7.9.0",
"@babel/preset-react": "^7.9.4",
"babel-loader": "^8.1.0",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11"
}
我假设不识别“typeof”运算符,但为什么呢?
我只是花了几个小时来处理这个确切的问题。
"@babel/preset-flow"
添加到您的.babelrc
文件(安装后)。这是推荐的here,但实际上对我不起作用。
对我有用的只是将
externals: { "react-native": true },
添加到我的 webpack.config.js
文件中。我的配置文件最终看起来像这样:
const path = require("path")
module.exports = {
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
},
externals: {
"react-native": true,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
// ...
],
},
}
我的理解是
react-native
是一个依赖项,所以 @babel/preset-flow
实际上并没有被触发来帮助解释这些文件中的 flow
格式 - 它可能只处理主要 "entry"
位置的文件webpack.config.js
文件.
希望这可以帮助那里的人。如果我有点偏离基础,请随时评论这个答案,我会更新这个:)
你尝试在浏览器中运行 React Native 吗?如果是,我建议使用 React Native for Web.
react-native
无法在浏览器中运行。需要在react-native
中添加一个从react-native-web
到webpack.config.js
的别名,所以用这个包代替。
按照 React Native for Web 文档,您需要对您的 webpack 配置进行此修改:
// webpack.config.js
module.exports = {
// ...the rest of your config
resolve: {
alias: {
'react-native$': 'react-native-web'
}
}
}
我将我的 expo 应用程序 SDK 从 43 升级到 48 并遇到了这个问题。如果您使用的是 expo react native,则此解决方案适合您。 复制此代码并粘贴到您的
babel.config.js
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: ['react-native-reanimated/plugin'],
};
};