NativeScript-VueをArchLinuxで動かす

## 本題：NativeScript-VueをArchLinuxで動かす

OS:ArchLinux

```zsh
% uname -a
Linux arch 5.14.16-arch1-1 #1 SMP PREEMPT Tue, 02 Nov 2021 22:22:59 +0000 x86_64 GNU/Linux

% cat /etc/*release
NAME="Arch Linux"
PRETTY_NAME="Arch Linux"
ID=arch
BUILD_ID=rolling
ANSI_COLOR="38;2;23;147;209"
HOME_URL="https://archlinux.org/"
DOCUMENTATION_URL="https://wiki.archlinux.org/"
SUPPORT_URL="https://bbs.archlinux.org/"
BUG_REPORT_URL="https://bugs.archlinux.org/"
LOGO=archlinux
```

AndroidエミュレータはGenymotionを使用.
とりあえずNativeScript-VueのテンプレートをVueCLIから生成する。

```zsh
% vue init nativescript-vue/vue-cli-template nsvueapp02                                                                    
? Project name nsvueapp02
? Project description A native application built with NativeScript-Vue
? Application name NativeScript-Vue Application
? Unique application identifier org.nativescript.application
? Project version 1.0.0
? Author [自分の名前＆メールアドレス]
? License MIT
? Select the programming language typescript
? Select a preset (more coming soon) Simple
? Install vuex? (state management) No
? Install vue-devtools? Yes
? Color scheme aqua

   vue-cli · Generated "nsvueapp02".
   vue-cli · cd nsvueapp02
   vue-cli · npm install
   vue-cli · ns preview
   vue-cli · # or
   vue-cli · ns run

% cd nsvueapp02
% npm install
```

これでNativeScript-Vueのテンプレートは出来た。
ここまではいい。

この次、さっそくアプリを起動しようとするとエラーが出た。

```zsh
# deviceオプションには、GenymotionでエミュレートしているAndroidの Device Identifier を指定している。
# なお接続しているデバイスもしくはエミュレータの Device Identifier は、「ns device」コマンドで表示できる
% ns run android --bundle --device 192.168.56.102:5555                                                                     
Searching for devices...
Your application will be deployed only on the device specified by the provided index or identifier.
Copying template files...
Platform android successfully added. v8.1.1
Preparing project...
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --config=/home/sig/my-repo/my-workbook01/nsvueapp02/webpack.config.js
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.hmr
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.externals=~/package.json
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.externals=package.json
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.android
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.appPath=src
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.appResourcesPath=App_Resources
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.nativescriptLibPath=/usr/lib/node_modules/nativescript/lib/nativescript-cli-lib.js
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.config=false
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --env.sourceMap
/home/sig/.nvm/versions/node/v15.14.0/bin/node: bad option: --watch
Executing webpack failed with exit code 9.
```

というわけで、ちゃんとアプリが動くように少しだけ作業が必要。
まずはNativeScript-Vueを動かすための前提条件が整っているかを確認する。

```zsh
% tns doctor
✔ Getting environment information 

No issues were detected.
✔ Your ANDROID_HOME environment variable is set and points to correct directory.
✔ Your adb from the Android SDK is correctly installed.
✔ The Android SDK is installed.
✔ A compatible Android SDK for compilation is found.
✔ Javac is installed and is configured properly.
✔ The Java Development Kit (JDK) is installed and is configured properly.
✔ Local builds for iOS can be executed only on a macOS system. To build for iOS on a different operating system, you can use the NativeScript cloud infrastructure.
✔ Getting NativeScript components versions information...
✔ Component nativescript has 8.1.4 version and is up to date.
⚠ Update available for component @nativescript/core. Your current version is 7.3.0 and the latest available version is 8.1.5.
✖ Component @nativescript/ios is not installed.
✔ Component @nativescript/android has 8.1.1 version and is up to date.
```

問題なし。iosがNGとなっているのはLinuxだからなので、とくに気にしない。
ios以外でなにか問題が表示されたら、内容に従って色々インストールするなりしましょう。

tns doctor でios以外問題がなくなったら、次はとりあえずNativeScriptを最新化してみる。
参考：https://www.nsdocjp.work/6/releases/upgrade-instructions.php

まずは tns migrate で既存プロジェクトを更新する。

※もし必要ならその前に`npm install -g nativescript`でNativeScriptツールを最新化すること。

```zsh
% tns migrate --force                                                                                                      
⚠ Git branch not clean, but using --force
✔ Pre-Migration verification complete
ℹ Backing up project files before migration
✔ Project files have been backed up
ℹ Cleaning up project files before migration
✔ Cleaned directory hooks
✔ Cleaned directory platforms
✔ Cleaned directory node_modules
✔ Cleaned file package-lock.json
✔ Project files have been cleaned up
ℹ Cleaning up old artifacts
✔ Cleaned old artifacts
ℹ Updating project dependencies
  - @nativescript/core has been updated to ~8.1.1
  - @nativescript/types has been updated to ~8.1.0
  - @nativescript/webpack has been updated to ~5.0.0
  - typescript has been updated to ~4.3.5
✔ Project dependencies have been updated
ℹ Updating tsconfig.json
✔ Updated tsconfig.json
✔ Cleaned file webpack.config.js
ℹ Initializing new webpack.config.js
✔ Initialized new webpack.config.js
ℹ Updated package.json main field to ./src/main.ts
✔ Applied ESLint fixes
✔ Migration complete.

Project has been successfully migrated. The next step is to run ns run <platform> to ensure everything is working properly.

Please note that you may need additional changes to complete the migration.
```

上記の後、さらに`tns update`でアプリケーションをアップグレードする。

```zsh
% tns update
This project is up to date.
```

なにやらすでに最新版になっていた模様。
これで動くはず、と動かしてみると...

```zsh
% ns run android --bundle --device 192.168.56.102:5555                                                                     
Searching for devices...
Your application will be deployed only on the device specified by the provided index or identifier.
npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)

added 693 packages, and audited 694 packages in 1m

49 packages are looking for funding
  run `npm fund` for details

5 vulnerabilities (2 moderate, 3 high)

To address all issues possible (including breaking changes), run:
  npm audit fix --force

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.
Copying template files...
Platform android successfully added. v8.1.1
Preparing project...
webpack is watching the files...
asset vendor.js 8.14 MiB [emitted] (name: vendor) (id hint: defaultVendor)
asset bundle.js 352 KiB [emitted] (name: bundle)
asset runtime.js 86.4 KiB [emitted] (name: runtime)
asset assets/images/NativeScript-Vue.png 8.22 KiB [emitted] [from: src/assets/images/NativeScript-Vue.png] [copied]
Entrypoint bundle 8.57 MiB = runtime.js 86.4 KiB vendor.js 8.14 MiB bundle.js 352 KiB
runtime modules 24.8 KiB 12 modules
orphan modules 356 bytes [orphan] 6 modules
modules by path ./node_modules/ 3.08 MiB
  modules by path ./node_modules/@nativescript/core/ 1.38 MiB 163 modules
  modules by path ./node_modules/css-tree/ 317 KiB 109 modules
  modules by path ./node_modules/source-map/lib/*.js 35.5 KiB 6 modules
  modules by path ./node_modules/reduce-css-calc/dist/ 131 KiB 5 modules
  modules by path ./node_modules/postcss-value-parser/lib/*.js 11.8 KiB 5 modules
  modules by path ./node_modules/@vue/devtools/ 641 KiB 3 modules
  modules by path ./node_modules/mdn-data/css/*.json 242 KiB 3 modules
modules by path ./src/ 127 KiB
  modules by path ./src/components/*.vue 4.65 KiB 7 modules
  ./src/main.ts 3.31 KiB [built] [code generated]
  ./src/app.scss 119 KiB [built] [code generated]
external "~/package.json" 42 bytes [optional] [built] [code generated]

LOG from ./node_modules/sass-loader/dist/cjs.js sass-loader ./node_modules/@nativescript/webpack/dist/loaders/apply-css-loader/index.js!./node_modules/@nativescript/webpack/dist/loaders/css2json-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/dist/cjs.js??clonedRuleSet-7[0].rules[0].use[3]!./node_modules/sass-loader/dist/cjs.js!./src/app.scss
<w> Deprecation Using / for division is deprecated and will be removed in Dart Sass 2.0.0.
<w> 
<w> Recommendation: math.div(blue($color) * 114, 1000)
<w> 
<w> More info and automated migrator: https://sass-lang.com/d/slash-div
<w> 
<w> node_modules/@nativescript/theme/scss/mixins/_utilities.scss 75:76  check-contrast()
<w> node_modules/@nativescript/theme/scss/mixins/_utilities.scss 84:49  alternate()
<w> node_modules/@nativescript/theme/scss/variables/_index.scss 56:11   @import
<w> node_modules/@nativescript/theme/scss/core/_index.scss 2:9          @import
<w> node_modules/@nativescript/theme/core.scss 8:9                      @import
<w> src/app.scss 3:9                                                    root stylesheet
<w> 
<w> Deprecation Using / for division is deprecated and will be removed in Dart Sass 2.0.0.
<w> 
<w> Recommendation: math.div(blue(#ffffff) * 114, 1000)
<w> 
<w> More info and automated migrator: https://sass-lang.com/d/slash-div
<w> 
<w> node_modules/@nativescript/theme/scss/mixins/_utilities.scss 76:73  check-contrast()
<w> node_modules/@nativescript/theme/scss/mixins/_utilities.scss 84:49  alternate()
<w> node_modules/@nativescript/theme/scss/variables/_index.scss 56:11   @import
<w> node_modules/@nativescript/theme/scss/core/_index.scss 2:9          @import
<w> node_modules/@nativescript/theme/core.scss 8:9                      @import
<w> src/app.scss 3:9                                                    root stylesheet
<w> 
<w> Deprecation Using / for division is deprecated and will be removed in Dart Sass 2.0.0.
<w> 
<w> Recommendation: math.div($light-color, 1.7)
<w> 
<w> More info and automated migrator: https://sass-lang.com/d/slash-div
<w> 
<w> node_modules/@nativescript/theme/scss/mixins/_utilities.scss 78:39  check-contrast()
<w> node_modules/@nativescript/theme/scss/mixins/_utilities.scss 84:49  alternate()
<w> node_modules/@nativescript/theme/scss/variables/_index.scss 56:11   @import
<w> node_modules/@nativescript/theme/scss/core/_index.scss 2:9          @import
<w> node_modules/@nativescript/theme/core.scss 8:9                      @import
<w> src/app.scss 3:9                                                    root stylesheet
<w> 

WARNING in ./node_modules/nativescript-vue-devtools/dist/index.js 48:27-67
Module not found: Error: Can't resolve '@triniwiz/nativescript-toasty' in '/home/sig/my-repo/my-workbook01/nsvueapp02/node_modules/nativescript-vue-devtools/dist'
 @ ./src/main.ts 5:0-52 7:12-23

WARNING in ./node_modules/nativescript-vue-devtools/dist/index.js 63:8-58
Module not found: Error: Can't resolve '@triniwiz/nativescript-socketio' in '/home/sig/my-repo/my-workbook01/nsvueapp02/node_modules/nativescript-vue-devtools/dist'
 @ ./src/main.ts 5:0-52 7:12-23

2 warnings have detailed information that is not shown.
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.

webpack 5.63.0 compiled with 2 warnings in 8642 ms
Webpack compilation complete. Watching for file changes.
No issues found.
Updating runtime package.json with configuration values...
Project successfully prepared (android)
Building project...
Gradle build...
         + setting applicationId
         + applying user-defined configuration from /home/sig/my-repo/my-workbook01/nsvueapp02/App_Resources/Android/app.gradle
         + adding nativescript runtime package dependency: nativescript-optimized-with-inspector
         + adding aar plugin dependency: /home/sig/my-repo/my-workbook01/nsvueapp02/node_modules/@nativescript/core/platforms/android/widgets-release.aar
         + adding aar plugin dependency: /home/sig/my-repo/my-workbook01/nsvueapp02/node_modules/nativescript-socketio/platforms/android/fancylogger-release.aar
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
注意:一部の入力ファイルは非推奨のAPIを使用またはオーバーライドしています。
注意:詳細は、-Xlint:deprecationオプションを指定して再コンパイルしてください。
Project successfully built.
The build result is located at: /home/sig/my-repo/my-workbook01/nsvueapp02/platforms/android/app/build/outputs/apk/debug/app-debug.apk
Installing on device 192.168.56.102:5555...
Successfully installed on device with identifier '192.168.56.102:5555'.
Restarting application on device 192.168.56.102:5555...
System.err: An uncaught Exception occurred on "main" thread.
System.err: Unable to create application com.tns.NativeScriptApplication: com.tns.NativeScriptException: Error calling module function 
System.err: ReferenceError: TNS_ENV is not defined
System.err: File: (file: src/webpack:/nsvueapp02/webpack/bootstrap:27:0)
System.err: 
System.err: StackTrace: 
System.err: ./src/main.ts(file: src/webpack:/nsvueapp02/src/main.ts:7:1)
System.err: 	at __webpack_require__(file: src/webpack:/nsvueapp02/webpack/bootstrap:24:0)
System.err: 	at __webpack_exec__(file:///data/data/org.nativescript.application/files/app/bundle.js:324:39)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:325:221)
System.err: 	at __webpack_require__.X(file: src/webpack:/nsvueapp02/webpack/runtime/startup entrypoint:6:0)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:325:47)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:330:3)
System.err: 	at require(:1:266)
System.err: 
System.err: 
System.err: ReferenceError: TNS_ENV is not defined
System.err: 
System.err: StackTrace:
System.err: java.lang.RuntimeException: Unable to create application com.tns.NativeScriptApplication: com.tns.NativeScriptException: Error calling module function 
System.err: ReferenceError: TNS_ENV is not defined
System.err: File: (file: src/webpack:/nsvueapp02/webpack/bootstrap:27:0)
System.err: 
System.err: StackTrace: 
System.err: ./src/main.ts(file: src/webpack:/nsvueapp02/src/main.ts:7:1)
System.err: 	at __webpack_require__(file: src/webpack:/nsvueapp02/webpack/bootstrap:24:0)
System.err: 	at __webpack_exec__(file:///data/data/org.nativescript.application/files/app/bundle.js:324:39)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:325:221)
System.err: 	at __webpack_require__.X(file: src/webpack:/nsvueapp02/webpack/runtime/startup entrypoint:6:0)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:325:47)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:330:3)
System.err: 	at require(:1:266)
System.err: 
System.err: 
System.err: ReferenceError: TNS_ENV is not defined
System.err: 	at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6465)
System.err: 	at android.app.ActivityThread.access$1300(ActivityThread.java:219)
System.err: 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)
System.err: 	at android.os.Handler.dispatchMessage(Handler.java:107)
System.err: 	at android.os.Looper.loop(Looper.java:214)
System.err: 	at android.app.ActivityThread.main(ActivityThread.java:7356)
System.err: 	at java.lang.reflect.Method.invoke(Native Method)
System.err: 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
System.err: 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
System.err: Caused by: com.tns.NativeScriptException: Error calling module function 
System.err: ReferenceError: TNS_ENV is not defined
System.err: File: (file: src/webpack:/nsvueapp02/webpack/bootstrap:27:0)
System.err: 
System.err: StackTrace: 
System.err: ./src/main.ts(file: src/webpack:/nsvueapp02/src/main.ts:7:1)
System.err: 	at __webpack_require__(file: src/webpack:/nsvueapp02/webpack/bootstrap:24:0)
System.err: 	at __webpack_exec__(file:///data/data/org.nativescript.application/files/app/bundle.js:324:39)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:325:221)
System.err: 	at __webpack_require__.X(file: src/webpack:/nsvueapp02/webpack/runtime/startup entrypoint:6:0)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:325:47)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:330:3)
System.err: 	at require(:1:266)
System.err: 
System.err: 
System.err: ReferenceError: TNS_ENV is not defined
System.err: 	at com.tns.Runtime.runModule(Native Method)
System.err: 	at com.tns.Runtime.runModule(Runtime.java:689)
System.err: 	at com.tns.Runtime.run(Runtime.java:681)
System.err: 	at com.tns.NativeScriptApplication.onCreate(NativeScriptApplication.java:21)
System.err: 	at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1189)
System.err: 	at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6460)
System.err: 	... 8 more
Successfully synced application org.nativescript.application on device 192.168.56.102:5555.
```

というわけで`ReferenceError: TNS_ENV is not defined`とのこと。
VueCLIが生成してくれたmain.tsで生じているようなので、ファイルを開いてみる。

```typescript:main.ts
import Vue from 'nativescript-vue'
import App from './components/App.vue'
import VueDevtools from 'nativescript-vue-devtools'

if(TNS_ENV !== 'production') {
  Vue.use(VueDevtools)
}


// Prints Vue logs when --env.production is *NOT* set while building
Vue.config.silent = (TNS_ENV === 'production')


new Vue({
  
  render: h => h('frame', [h(App)])
}).$start()
```

本来ならTNS_ENVには、起動モードを判定するための文字列がWebpackにより設定されているはず。
しかしこれがReferenceErrorになるということは...

ということで、webpack.config.jsをみてみる。

```js:webpack.config.js
const webpack = require("@nativescript/webpack");

module.exports = (env) => {
	webpack.init(env);

	// Learn how to customize:
	// https://docs.nativescript.org/webpack

	return webpack.resolveConfig();
};
```

本来ならここで、TNS_ENVがモジュール間で使えるように定義があったはず。
どうやら`tns migrate`を実行したことで、定義が消えてしまったようだ。

なので、改めてここにTNS_ENVの定義を行う必要がある。
DefinePluginを使って、TNS_ENVを定義しましょう。
ついでにそのほかの足りていない環境変数もここで追加します。

```js:webpack.config.js
const webpack = require("@nativescript/webpack");
const { DefinePlugin } = require('webpack');

module.exports = (env) => {
	webpack.init(env);

	const {
		production, // --env.production
	} = env;
	const mode = production ? "production" : "development"
	const platform = env && (env.android && "android" || env.ios && "ios" || env.platform);

	webpack.chainWebpack(config => {
		config.plugin('DefinePlugin').use(DefinePlugin, [
			{
				"TNS_ENV": JSON.stringify(mode),
				'global.TNS_WEBPACK': 'true',
				'global.isAndroid': platform === 'android',
				'global.isIOS': platform === 'ios',
				process: 'global.process',

			}
		])
	});

	return webpack.resolveConfig();
};

```

これでTNS_ENVが正しく定義されたはず。
改めてアプリを起動してみると...

```zsh
% ns run android --bundle --device 192.168.56.102:5555                                                                     
（中略）
System.err: ReferenceError: __UI_USE_EXTERNAL_RENDERER__ is not defined
System.err: File: (file: src/webpack:/nsvueapp02/webpack/bootstrap:27:0)
System.err: 
System.err: StackTrace: 
System.err: ./node_modules/@nativescript/core/bundle-entry-points.js(file: src/webpack:/nsvueapp02/node_modules/@nativescript/core/bundle-entry-points.js:6:0)
System.err: 	at __webpack_require__(file: src/webpack:/nsvueapp02/webpack/bootstrap:24:0)
System.err: 	at __webpack_exec__(file:///data/data/org.nativescript.application/files/app/bundle.js:331:39)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:332:143)
System.err: 	at __webpack_require__.X(file: src/webpack:/nsvueapp02/webpack/runtime/startup entrypoint:6:0)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:332:47)
System.err: 	at (file:///data/data/org.nativescript.application/files/app/bundle.js:337:3)
System.err: 	at require(:1:266)
```

なにやらまだ必要な変数があるらしい。
NativeScriptの本家ブログを読むと、NativeScriptバージョン8.1以降で@nativescript/webpack 4.1（もしくはそれ以前）以前と共存するには、DefinePluginでいくつかモジュール間変数を定義してやる必要があるらしい。

（そうしないと`ReferenceError: __UI_USE_EXTERNAL_RENDERER__ is not defined`のようなエラーが出る、と書かれている）

https://blog.nativescript.org/nativescript-8-1-announcement/index.html#using-8.1-with-webpack-4.x.x%3F

というわけで現在のNativeScriptのバージョンを確認。

```zsh
% npm ls @nativescript/core
nsvueapp02@1.0.0 /home/sig/my-repo/my-workbook01/nsvueapp02
└── @nativescript/core@8.1.5 

% npm ls @nativescript/webpack
nsvueapp02@1.0.0 /home/sig/my-repo/my-workbook01/nsvueapp02
└── @nativescript/webpack@5.0.0 
```

@nativescript/webpackは5.0.0。バージョン的には問題ないはずだが、実際に`__UI_USE_EXTERNAL_RENDERER__`が出力されたわけなので、ひとまずDefinePluginにいくつかモジュール間変数を定義する。

```js:webpack.config.js
const webpack = require("@nativescript/webpack");
const { DefinePlugin } = require('webpack');

module.exports = (env) => {
	webpack.init(env);

	const {
		production, // --env.production
	} = env;
	const mode = production ? "production" : "development"
	const platform = env && (env.android && "android" || env.ios && "ios" || env.platform);

	webpack.chainWebpack(config => {
		config.plugin('DefinePlugin').use(DefinePlugin, [
			{
				"TNS_ENV": JSON.stringify(mode),
				'global.TNS_WEBPACK': 'true',
				'global.isAndroid': platform === 'android',
				'global.isIOS': platform === 'ios',
				process: 'global.process',

				__UI_USE_XML_PARSER__: true,
				__UI_USE_EXTERNAL_RENDERER__: false,
				__CSS_PARSER__: JSON.stringify('css-tree')
			}
		])
	});

	return webpack.resolveConfig();
};
```

これでもう一度実行してみると...

```zsh
% ns run android --bundle --device 192.168.56.102:5555
（中略）
Successfully synced application org.nativescript.application on device 192.168.56.102:5555.
```

![Screenshot from 2021-11-12 08-04-07.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/267156/a3ba1978-e97f-b0b2-8b67-06135f627658.png)


起動した！

ちなみにmain.tsでTNS_ENVがproduction以外の場合に `Vue.use(VueDevtools)` で Vue Developer Tools を利用するようにしているが、これはこの段階ではまだうまく動かない。

VueDevToolsを使うことができるようにするには、下記ページの手順に従えばいい。
https://nativescript-vue.org/en/docs/getting-started/vue-devtools/

※なお同様のページの日本語版も存在するが、現在こちらは情報が少し古いようで正常に動作してくれない。
https://nativescript-vue.org/ja/docs/getting-started/vue-devtools/

そういうわけで、本家英語版の手順に沿って下記を実施する。

```xml:AndroidManifest.xml
<application
  （中略。Android APIレベル28以上でVueDevToolsを動かすなら下記を追加）
  android:usesCleartextTraffic="true"
>
```

```zsh
# 必要なものをインストール
% npm install --save @vue/devtools@5.3.4 @triniwiz/nativescript-toasty @triniwiz/nativescript-socketio@4.0.1 nativescript-vue-devtools

# いったんplatformsディレクトリを削除して
% rm -rf platforms

# VueDevToolsを起動
% npx vue-devtools  

# あらためてアプリを起動
% ns run android --bundle --device 192.168.56.102:5555
```

これでVueDevToolsも動作するようになりました。

![Screenshot from 2021-11-12 08-35-53.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/267156/23025c9d-bf86-ec86-e253-7692f10a124a.png)

※なお筆者はAndroidエミュレータにGenymotionを利用しているので、main.tsのVue.use()を下記のように書き換えています。

```typescript:main.ts
// AsIs
// Vue.use(VueDevtools)

// ToBe（ここでのhostとは、Androidから見た 'VueDevtoolsを実行しているホスト環境' のことなので、Genymotionにおけるホスト端末のアドレス「10.0.3.2」を指定）
Vue.use(VueDevtools, { host: '10.0.3.2' })
```

## 著者プロフィール

faable01です。かつては創作仲間と小説を書いたり、製菓業界で楽しくやっていたはずが、紆余曲折を経て、サーバーレス技術を触るのが好きなITエンジニアになっていました。AWSのIaC兼サーバレス爆速開発ツール **「SST」** が好きです。個人ブログでもたまに記事を書いています。

https://signote.link

それから、業務日報SaaS **「RevisNote」** を運営しています。リッチテキストでの日報と、短文SNS感のある分報を書けるのが特徴で、組織に所属する人数での従量課金制です。アカウント開設後すぐ使えて、無料プランもあるから、気軽にお試しください。

https://revisnote.com?1710501811980