RN 走起!

未完,累~~~~

1.安装



2.创建React Native 项目:

react-native init rn001

完成后可以看到相应的提示:

To run your app on iOS:
   cd /Users/muzico/Documents/Project/reactnative/20180816/rn001
   react-native run-ios
   - or -
   Open ios/rn001.xcodeproj in Xcode
   Hit the Run button
To run your app on Android:
   cd /Users/muzico/Documents/Project/reactnative/20180816/rn001
   Have an Android emulator running (quickest way to get started), or a device connected
   react-native run-android

3.进入该目录下:

cd rn001

4.加入第三方

yarn add babel-polyfill react-dom react-native-web
yarn add -D assets-webpack-plugin babel-loader babel-preset-env babel-preset-react babel-preset-stage-2 file-loader source-map-loader url-loader webpack webpack-dev-server

5.创建 src 文件夹
6.将 App.js文件 放入 src文件夹中。
7.修改 index.js里面关于 App.js 的路径。

/** @format */

import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

8.在 rn001目录下,创建 index.web.js 文件:

import { AppRegistry } from 'react-native';
import React from 'react';
import App from './src/App';

AppRegistry.registerComponent('rnweb', () => App);
AppRegistry.runApplication('rnweb', {
  initialProps: {
  },
  rootTag: document.getElementById('react-root')
});

9.在 rn001目录下,创建 index.html 文件:

<!DOCTYPE html>
<meta charset="utf-8">
<title>rnweb</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>*{font-family: -apple-system, "Helvetica Neue", Helvetica, "Nimbus Sans L", Arial, "Liberation Sans", "PingFang SC", "Hiragino Sans GB", "Source Han Sans CN", "Source Han Sans SC", "Microsoft YaHei", "Wenquanyi Micro Hei", "WenQuanYi Zen Hei", "ST Heiti", SimHei, "WenQuanYi Zen Hei Sharp", sans-serif;}</style>
<div id="react-root"></div>
<script src="/static/bundle.js"></script>

这个HTML文件将会成为 react-native 在 web 上的入口文件,加载内容。

10.创建 webpack.config.js

var webpack = require('webpack');
var path = require('path');
var AssetsPlugin = require('assets-webpack-plugin');
// const WpPluginWatchOffset = require('wp-plugin-watch-offset');

module.exports = {
    stats: { assets: true, children: false, chunks: false, modules: false, source: false },
    entry: {
        bundle: path.join(__dirname, 'index.web'),
    },
    plugins: [
        // new AssetsPlugin({ filename: 'build/manifest.json', prettyPrint: true }),
        new webpack.DefinePlugin({
            'typeof __DEV__': JSON.stringify('boolean'),
            '__DEV__': JSON.stringify(true),
            'process.env.NODE_ENV': JSON.stringify('development'),
        }),
    ],
    resolve: {
        extensions: ['.js', '.json', '.android.js', '.ios.js'],
        alias: { 'react-native': 'react-native-web' },
        modules: ['web_modules', 'node_modules'],
    },
    module: {
        loaders: [
            {
                exclude: [
                    /\.html$/,
                    /\.(js|jsx)$/,
                    /\.css$/,
                    /\.json$/,
                    /\.svg$/,
                ],
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        name: 'media/[name].[hash:8].[ext]',
                        emitFile: true,
                    },
                }],
            },
            {
                test: /\.(js|jsx)$/,
                include: [
                    path.resolve(__dirname, 'src'),
                ],
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            cacheDirectory: true,
                            plugins: [
                                "react-native-web/babel"
                            ],
                        },
                    },
                    {
                        loader: 'source-map-loader',
                    },
                ],
            },
            {
                test: /\.json$/,
                use: 'json-loader',
            },
            {
                test: /\.svg$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: 'media/[name].[hash:8].[ext]',
                        emitFile: true,
                    },
                }],
            },
        ],
    },
    output: {
        libraryTarget: 'umd',
        path: path.join(__dirname, '..', 'build'),
        publicPath: '/static/',
        filename: '[name].js',
        chunkFilename: '[name].js',
    },
    devtool: 'inline-source-map',
};

11.编辑 package.json

"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },

加入 web 脚本命令:

"web": "node node_modules/webpack-dev-server/bin/webpack-dev-server -w"

12.运行 web

yarn run web

13.出现了提示,需要安装某内容才能运行上面的语法:

提示内容:

The CLI moved into a separate package: webpack-cli.
Please install 'webpack-cli' in addition to webpack itself to use the CLI.
-> When using npm: npm install webpack-cli -D
-> When using yarn: yarn add webpack-cli -D

执行:

yarn add webpack-cli -D

14.再次执行:

yarn run web

出现了错误提示:

yarn run v1.6.0
$ node node_modules/webpack-dev-server/bin/webpack-dev-server -w
✖ 「wds」: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'loaders'. These properties are valid:
   object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, defaultRules?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }
   -> Options affecting the normal modules (`NormalModuleFactory`).
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

这个问题,实际上根据网上的说法是因为 webpack 版本问题导致的。

把module里的那个loaders改成rules

我当前的的webpack 版本是 4.16.5,
按照上面的提示将webpack.config.js 文件的module里的那个loaders改成rules。
然后重新执行,顺利通过了.............然后产生了新的问题。

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

ERROR in ./src/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Plugin 0 specified in "/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-preset-react-native/index.js" provided an invalid property of "default" (While processing preset: "/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-preset-react-native/index.js")
    at Plugin.init (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/plugin.js:131:13)
    at Function.normalisePlugin (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:152:12)
    at /Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
    at Array.map (<anonymous>)
    at Function.normalisePlugins (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at /Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
    at /Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
    at Array.map (<anonymous>)
    at OptionManager.resolvePresets (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
    at OptionManager.mergePresets (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
    at OptionManager.mergeOptions (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
    at OptionManager.init (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
 @ ./index.web.js 3:0-28 5:45-48
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./index.web

ERROR in ./node_modules/react-native-web/dist/exports/ART/index.js
Module not found: Error: Can't resolve 'react-art' in '/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/react-native-web/dist/exports/ART'
 @ ./node_modules/react-native-web/dist/exports/ART/index.js 1:0-28 2:15-18
 @ ./node_modules/react-native-web/dist/index.js
 @ ./index.web.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./index.web
ℹ 「wdm」: Failed to compile.


修改 webpack.config.js 的 resolve 里面的 alias 内容,增加:

'react-art': 'ART'

即为:

alias: { 'react-native': 'react-native-web','react-art': 'ART' },

再重新运行:

yarn run web

把一部分的问题解决了,还有一部分问题没有解决:

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

ERROR in ./src/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Plugin 0 specified in "/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-preset-react-native/index.js" provided an invalid property of "default" (While processing preset: "/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-preset-react-native/index.js")
    at Plugin.init (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/plugin.js:131:13)
    at Function.normalisePlugin (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:152:12)
    at /Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
    at Array.map (<anonymous>)
    at Function.normalisePlugins (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at /Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
    at /Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
    at Array.map (<anonymous>)
    at OptionManager.resolvePresets (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
    at OptionManager.mergePresets (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
    at OptionManager.mergeOptions (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
    at OptionManager.init (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
 @ ./index.web.js 3:0-28 5:45-48
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./index.web
ℹ 「wdm」: Failed to compile.

执行:

yarn add babel-preset-react-native -D

再次运行:

yarn run web

这个问题解决了,新的问题出现了:

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

ERROR in ./src/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
ReferenceError: Unknown plugin "react-native-web/babel" specified in "base" at 0, attempted to resolve relative to "/Users/muzico/Documents/Project/reactnative/20180816/rn001/src"
    at /Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17
    at Array.map (<anonymous>)
    at Function.normalisePlugins (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at OptionManager.init (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-loader/lib/index.js:50:20)
    at /Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-loader/lib/fs-cache.js:118:18
    at ReadFileContext.callback (/Users/muzico/Documents/Project/reactnative/20180816/rn001/node_modules/babel-loader/lib/fs-cache.js:31:21)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)
 @ ./index.web.js 3:0-28 5:45-48
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./index.web
ℹ 「wdm」: Failed to compile.