1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

備忘:Monaca (Onsen UI V2) + React + ncmb

Posted at

前提

  • MonacaでReactフレームワークを使ったプロジェクトがある状態
    • テンプレートはOnsen UI V2 Tabbar
  • ニフクラMobile Backendでアプリがある状態
    • アプリのapiKeyとclientKeyが必要

ncmbのインストール

ターミナルからインストールすると/node_modules/ncmbが追加される.

npm install ncmb -S

参考:https://www.npmjs.com/package/ncmb

ncmb APIを使うコードを追加

手っ取り早く試すために,/src/HomePage.jsxに以下を追加.
(まだReact勉強中だけど,本当はvarじゃなくてconstとかletを使うべき?)

 export default class HomePage extends React.Component {
   render() {
+    var apiKey    = "your_ncmb_apiKey";
+    var clientKey = "your_ncmb_clientKey";
+    var NCMB = require('ncmb');
+    var ncmb = new NCMB(apiKey, clientKey);
+    if (!ncmb) {
+      console.log("ncmb is null.");
+    } else {
+      console.log("ncmb is loaded.");
+    }
     return (
       <Page renderToolbar={() =>

fsの解決

このままだと

ERROR in ./node_modules/node-localstorage/LocalStorage.js
Module not found: Error: Can't resolve 'fs' in '...\node_modules\node-localstorage'

というエラーがでるので,/webpack.config.jsに以下を追加.

   performance: {
     hints: false
-  }
+  },
+
+  node: {
+    fs: 'empty'
   }
 };

参考:
https://github.com/lmaccherone/node-localstorage/issues/45
https://github.com/lmaccherone/node-localstorage/issues/35
https://qiita.com/Hoshito/items/f7acb1b2082f8c2d0bd3

apikey and clientkey requredの解決

コンパイル(トランスパイル?)は解決するけど,実行結果を見るとエラーが出る.

vendors~app.js:40 Error: apikey and clientkey required
    at Object.e (vendors~app.js:48)
    at Object.<anonymous> (vendors~app.js:48)
    at l (runtime~app.js:1)
    at t.value (app.js:1)
    at Ba (vendors~app.js:40)
    at Da (vendors~app.js:40)
    at vs (vendors~app.js:40)
    at lu (vendors~app.js:40)
    at su (vendors~app.js:40)
    at Qs (vendors~app.js:40)

これは新しいWebpackのDefineの使い方に問題があるっぽい?
とりあえず,/node_modules/ncmb/lib/ncmb.jsを編集して,問題箇所をコメントアウト.

     return NCMB;
   })();
+  /*
   if (typeof define === 'function' && define.amd) {
    define([], NCMB);
   }
+  */
   if(typeof window !== "undefined"){
     window.NCMB = NCMB;
   }

参考:
https://github.com/NIFCloud-mbaas/UserCommunity/issues/456
https://github.com/for-GET/know-your-http-well/issues/60
https://github.com/webpack/webpack/issues/5316#issuecomment-395778081
https://www.npmjs.com/package/amdefine#amdefineintercept-usage

結果

とりあえず,以上のステップで,ncmb APIが使えるようになった.
(確認したのは,login()だけ)

ncmb is loaded.
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?