diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..6ef5839 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,2 @@ +node_modules/ +generator/templates/ \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..cc7dc36 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,36 @@ +module.exports = { + "root": true, + "env": { + "node": true + }, + "extends": [ + "eslint:recommended", + "plugin:vue/recommended", + "@vue/airbnb", + "@vue/prettier" + ], + "rules": { + "import/extensions": 0, + "global-require": 0, + "eol-last": 0, + "no-param-reassign": 0, + "object-curly-newline": 0, + "no-plusplus": 0, + "max-len": [ + 2, + { + "code": 160 + } + ], + "prefer-destructuring": [ + 2, + { + "object": true, + "array": false + } + ] + }, + "parserOptions": { + "parser": "babel-eslint" + } +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 40b878d..18566ec 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -node_modules/ \ No newline at end of file +node_modules/ +.vscode \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..95668c3 --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +generator/templates/* \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..f0f8e68 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,10 @@ +{ + "printWidth": 160, + "singleQuote": true, + "trailingComma": "none", + "tabWidth": 2, + "semicolons": true, + "bracketSpacing": true, + "arrowParens": "always", + "useTabs": false +} \ No newline at end of file diff --git a/README.md b/README.md index f80b854..0341b43 100644 --- a/README.md +++ b/README.md @@ -1 +1,242 @@ -# nativescript-vue-cli-plugin \ No newline at end of file +# nativescript-vue-cli-plugin + +Nativescript-Vue Plugin for [vue-cli@3.0](https://github.com/vuejs/vue-cli) + +This plugin will integrate [Nativescript-Vue](https://nativescript-vue.org/) into new and existing Vue projects. Additionally, it will allow for the choice of developing for Native only environments or Native __and__ Web environments under a single project structure. In addition, choosing to integrate [Nativescript-Vue-Web](https://github.com/Nativescript-Vue-Web/Nativescript-Vue-Web), will allow for the development of Web components with a NativeScript-Vue like syntax that has the benefit of allowing for the sharing of components between the Native and Web sides of the project. This helps reduce the amount of code, maintenence needs, and the amount of time needed for development activities. + +## Sharing logic in a single Web and Native capable component +The key feature of this plugin is that it will allow you to compose SFC's that contain both Web and Native structures in them. If your component has exactly the same logic (` + + +``` + +### Optional Separation of concerns for Web and Native SFC's +If you want complete seperation of concerns between Web and Native for components, core logic and styling, you can also provide an alternate file naming scheme in your project. The name will dictate which mode (Web or Native) and platform (Android or IOS) the file will be used with. The same overall schema will work for `.vue`, `.js`, `.ts`, `.scss` and `.css` files. + +| File Type | Android __and__ IOS | Android only | IOS only | Web only | +| ---------- | ------------------- | --------------- | --------------- | --------------- | +| vue | *.native.vue | *.android.vue | *.ios.vue | *.vue | +| js | *.native.js | *.android.js | *.ios.js | *.js | +| ts | *.native.ts | *.android.ts | *.ios.ts | *.ts | +| scss | *.native.scss | *.android.scss | *.ios.scss | *.scss | +| css | *.native.css | *.android.css | *.ios.css | *.css | + +Webpack will handle figuring out which files to include based on the `npm run` command syntax you pass in. You can also mix and match this file naming schema with the `web` or `native` tag options mentioned above. + +At `serve` or `build` in conjunction with the mode such as `android` or `ios`, Webpack will filter which files are looked at. For instance, if you do `npm run serve:android`, then it will look for `*.native.vue` and `*.android.vue` files and ignore `*.ios.vue` files entirely. Conversely, it will do the same when you are working with `ios` and will ignore `*.android.vue` files. + +This will allow you to develop generic native components under the `*.native.vue` file extension, but in special cases, it may require you to do platform specific components, core logic and styling. Use the corrosponding file extension to allow this to happen. + +If you are building for web, then just `*.vue` will work and if you are building for a Native __only__ project, then `*.vue` will work as well as the previous options mentioned. + +## Sharing components and assets between Native and Web SFC's +If you want to use common components and assets between `web`, `android` and `ios`, you can do that. For `assets`, place them in `src/assets` and for components, place them in `src/components`. At compile time, assets will be copied to the output directory's `assets` folder and can be universally accessed across environments via something like `~/assets/logo.png`. For components, they can be universally accessed via something similar to `components/HelloWorld`. + +## Install + +If vue-cli 3 is not yet installed, first follow the instructions here: https://github.com/vuejs/vue-cli + +**Tip**: If you don't want to overwrite your current vue-cli 2 setup because you still need `vue init`, [then try this](https://cli.vuejs.org/guide/creating-a-project.html#pulling-2-x-templates-legacy). + +Generate a project using vue-cli 3.0 +``` +vue create my-app +``` + +Before installing the Nativescript-Vue CLI 3 Plugin, make sure to commit or stash changes in case you need to revert. + +To install the Nativescript-Vue CLI 3 Plugin... +``` +cd my-app +npm install --save-dev git+https://github.com/jawa-the-hutt/vue-cli-plugin-nativescript-vue +vue invoke vue-cli-plugin-nativescript-vue +``` + +## Invocation Prompts +1. Enter a unique application identifier + * Accepting the default is fine for testing +2. Use HTML5 history mode? (Default: hash mode) + * Required parameter for the cli core generator when vue-router is used +3. Is this a brand new project? (Default: Yes) + * By choosing `No`, the plugin will try and be as non-destructive as possible to an existing project. It will do this by adding a folder into root named `ns-example` and add files into there to provide examples of how a project would change. + * These changes will factor in answers to the other questions and adjust accordingly. Regardless of the answer, the plugin will install packages and adjust `package.json` as necessary to prep the project. +4. Dual Native AND Web development experience or a Native only? (Default: Dual) + * By default, the plugin will assume you want to develop for the Web and Native environments within the same project. As such, there will be two sides to the project where web environments will be actively developed within `/src` and Native environments will be developed within `/app` unless you choose to integrate `Nativescript-Vue-Web` and all files will be placed in `/src`. + * Warning: Choosing to develop for Native only will move the main entry point of the project and development folder to `/app`, it will copy the necessary files and then delete `/src`. + * By choosing `Dual`, you will be able to bring your own component framework into the web portion of the project. `NativeScript-Vue` [cannot use vue-router](https://nativescript-vue.org/en/docs/routing/vue-router/) currently, so you will have to provide your own manual routing. The templated options deployed with the plugin will show how to do basic manual routing. +5. What type of template do you want to start with? (Default: Simple) + * Simple is just a simple setup with a header and basic routing. + * [Nativescript-Vue-Web](https://github.com/Nativescript-Vue-Web/Nativescript-Vue-Web) - The Simple template, but with NS-Vue like syntax for web components. This option should only appear if you have chosen to develop in the Dual Web and Native environments. This option will effecively integrate a web component framework that will allow you to develop components that can be used in the Web and Native side of the project. It uses `NativeScript-Vue` like syntax on components which will allow for the sharing of components between NativeScript and Web. + * Sidebar (currently disabled), will allow you to start with a project that includes a fixed header and pop-out sidebar menu. + * We expect to add more templates in the future as use cases come up. + +## Running the project +You will have several options in serving and building the project: +1. `npm run serve:web` +2. `npm run serve:android` +3. `npm run serve:ios` +4. `npm run build:web` +5. `npm run build:android` +6. `npm run build:ios` + + +The basic `serve` and `build` options should be similar to what is in a CLI 3 project except the added options to dictate which kind of environment you are using: `web`, `android` or `ios`. Please note that when building web projects, they will output to `dist` and when building native projects, they will output to `platforms\android` or `platforms\ios` depending on which you are building at the time. + +### Debugging your project +You will have the standard options for debugging available to you as you would with just `tns`. You can do the following to debug Native versions of your app. +1. `npm run debug:android` +2. `npm run debug:ios` + +You should then be able to attach the Chrome debugger as you normally would via the [NativeScript docs](https://docs.nativescript.org/angular/tooling/debugging/chrome-devtools). + +You should also be able to debug directly in VSCode. The [NativeScript VSCode Extension docs](https://docs.nativescript.org/angular/tooling/visual-studio-code-extension) are a good place to start with understanding how to do this. However, you will need to modify your `launch.json` file to force `tns` to work properly with VUE CLI 3. + +Your `launch.json` file should look something like below. Notice the different in the `tnsArgs` line that is different than what is in the documentation link above. +``` +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch on iOS", + "type": "nativescript", + "request": "launch", + "platform": "ios", + "appRoot": "${workspaceRoot}", + "sourceMaps": true, + "watch": true, + "tnsArgs":[" --bundle --env.development cross-env-shell VUE_CLI_MODE=development.ios"] + }, + { + "name": "Attach on iOS", + "type": "nativescript", + "request": "attach", + "platform": "ios", + "appRoot": "${workspaceRoot}", + "sourceMaps": true, + "watch": false + }, + { + "name": "Launch on Android", + "type": "nativescript", + "request": "launch", + "platform": "android", + "appRoot": "${workspaceRoot}", + "sourceMaps": true, + "watch": true, + "tnsArgs":[" --bundle --env.development cross-env-shell VUE_CLI_MODE=development.android"] + }, + { + "name": "Attach on Android", + "type": "nativescript", + "request": "attach", + "platform": "android", + "appRoot": "${workspaceRoot}", + "sourceMaps": true, + "watch": false + }, + { + "type": "chrome", + "request": "launch", + "name": "web: chrome", + "url": "http://localhost:8080", + "webRoot": "${workspaceFolder}/src", + "breakOnLoad": true, + "sourceMapPathOverrides": { + "webpack:///src/*": "${webRoot}/*" + } + }, + ] +} +``` +You will also need to modify your `vue.config.js` file to include a `webpack-chain` statement that will setup your source map. It should look something like this: +``` +module.exports = { + chainWebpack: config => { + config + .devtool('inline-source-map') + } +} +``` + +### Previewing your Project +You should be able to use the NativeScript Playground and Preview Apps via the following npm statements: +1. `npm run preview:android` +2. `npm run preview:ios` + +#### --env command line recognition +Basic support for passing the `env` command line option is in place, but has a slightly different syntax since we're working with the CLI 3 webpack infrastructure. To inject items into `env` at run-time, you will need to add `-- --env.option` Where option is one of the recognized options that Nativescript-Vue and this project supports. +An example of this would be something like this: `npm run serve:android -- --env.production`. This would allow you to serve up a Production build of your Android app versus just running `npm run serve:android` which would serve a Development version of the same. + +#### Webpack related information +The options passed in at `npm run` will dictate what webpack config is provided. The first choice webpack will make is if this is a `web` or `native` environment. Then, if it's a `native` environment, it will determine choices to be made between `ios` and `android`. + +Each time the project is built or served, the plugin will copy the latest webpack config from the cli to the root of your project. When you build a project, it will clean-up this file at the end, but just serving the project will not. This is an issue with [nativescript-dev-webpack](https://github.com/NativeScript/nativescript-dev-webpack) and cannot be overcome at this time. + +#### Inspecting the Webpack config +If you'd like to see what the webpack config is doing then you can run one of the following: + +1. `vue inspect -- --env.android > out-android.js` +2. `vue inspect -- --env.ios > out-ios.js` +3. `vue inspect -- --env.web > out-web.js` + +These will default to showing you the Development version of the webpack config. You can pass in the `-- --env.production` option to see the Production version of the config. Subtitute `development.android` or `production.ios`, etc to see the different configs based on the environmental variables. + +#### Aliases +Prebuilt in the webpack config are several aliases that you can use. Here is a table listing out the various alias and the folder they use based on the environment chosen: + +| Alias | Native | Web | +| ---------- | --------------- | --------------- | +| ~ | /app | /src | +| @ | /app | /src | +| src | /src | /src | +| assets | /src/assets | /src/assets | +| components | /src/components | /src/components | +| fonts | /src/fonts | /src/fonts | +| styles | /src/styles | /src/styles | +| root | / | / | + + +## For TypeScript enabled projects +If your CLI 3 project has TypeScript enabled, then the plugin will attempt to give you a very basic TypeScript version of the template you choose. When you invoke the plugin and the template generator makes changes, you will notice the `*.d.ts` files that are usually in `src` will be moved to `/types`. The plugin's webpack integration will ensure these files are referenced correctly at compile and runtimes. diff --git a/generator/README.md b/generator/README.md new file mode 100644 index 0000000..3167cfc --- /dev/null +++ b/generator/README.md @@ -0,0 +1,32 @@ +# nativescript-vue-cli-plugin - Generator Readme + +Want to submit a PR for a new template? Read below. + +It is __highly, highly, highly suggested__ that you copy/paste the `simple` template in its entirety and then rename the copied directory. It will make it much easier for you to get started using the existing logic in the generator. Modifications to the existing generator logic will be considered for PR, but will have to go through rigourous testing to ensure the changes do not break all pre-existing templates. + +If you want to add additional templates to the plugin, then here's the information on how to do it: + +1. Create a new option to the prompt question #5 concerning which template you'd like to deploy. + * The value for the template should be kept simple and easy. +2. Create a new directory under `/generator/templates`. + * The directory name should __exactly match__ the value from #1. For example if the value from #1 is `simple`, then the directory structure would be `/generator/templates/simple` +3. The new template directory __must__ have a single first-level subdirectory named `src`. +4. Inside the `src` directory, you should add the following in an effort to give the template feature consistancy to the other templates: + * router.js + * main.js + * main.native.js (the NS-Vue project entry point) + * package.json (this is the standard NativeScript-Vue package.json file. Just copy/paste from the simple template) + * App.vue + * views/About.vue (optional) + * views/Home.vue (optional) + * components/HelloWorld.vue (optional) + * components/HelloWorld.native.vue (optional) + * components/HelloWorld.ios.vue (optional) + * components/HelloWorld.android.vue (optional) + * assets/logo.png (optional, but highly encouraged to prove images are loading) + +Within the \*.vue files you will find [ejs](https://github.com/mde/ejs) syntax that will enable you to differentiate between TypeScript and non-TypeScript projects. Any new templates added to the project __must__ demonstrate they work across these options or the PR to add the template will be rejected. + +### Word of warning concerning using EJS templates with Prettier +Prettier does not support EJS templates and if you have Prettier automatically fix all issues in a `*.vue` template file, then you will run the risk of it overwriting sections of the template from one `if` statement to the `else` side of the statement. Pay close attention to this specifically in your `script` tags as it relates to the TypeScript vs. non-TypeScript parts of the template. Whichever one comes first in the `if` statement will overwrite the section after the `else` statement. + diff --git a/generator/index.js b/generator/index.js index f376dc6..029df3e 100644 --- a/generator/index.js +++ b/generator/index.js @@ -1,44 +1,931 @@ -module.exports = (api, options, rootOptions) => { - const fs = require('fs') - const rimraf = require('rimraf') +/* eslint-disable no-console */ +const path = require('path'); +const fs = require('fs-extra'); +const replace = require('replace-in-file'); - api.extendPackage({ - scripts: { - 'watch:android': 'vue-cli-service tns --android', - 'watch:ios': 'vue-cli-service tns --ios', - }, - dependencies: { - 'nativescript-vue': '^1.3.1' +const newline = process.platform === 'win32' ? '\r\n' : '\n'; + +module.exports = async (api, options, rootOptions) => { + const genConfig = { + // if it is a new project changes will be written as they normally would with any plugin + // if it is an existing project, changes will be added to the ./ns-example directory + dirPathPrefix: options.isNewProject === true ? './' : './ns-example/', + + // simple typescript detection and then variable is passed to multiple templating functions + // to simply change the file's extension + jsOrTs: api.hasPlugin('typescript') ? '.ts' : '.js', + + // A template type of 'simple' project will have a base template path that equals: ./templates/simple + // then we determine if the project is using Nativescript-Vue-Web and we append a subdirectory to the base path + templateTypePathModifer: options.templateType, + + // Get the location to the native app directory + nativeAppPathModifier: options.isNativeOnly ? 'app/' : 'src/', + + // Determine the path to App_Resources + get appResourcesPathModifier() { + return this.nativeAppPathModifier + 'App_Resources'; }, - devDependencies: { - 'nativescript-vue-loader': '1.0.0', - 'nativescript-vue-template-compiler': '^1.3.1', - 'tns-core-modules': '^4.0.0' - } - }) - api.extendPackage(pkg => { - delete pkg.dependencies['vue'] - delete pkg.devDependencies['vue-template-compiler'] - delete pkg.browserslist - delete pkg.scripts['serve'] - }) + // setup directories to exclude in the tsconfig.json file(s) + get tsExclusionArray() { + return ['node_modules', 'dist', 'platforms', 'hooks', this.appResourcesPathModifier]; + } + }; - api.render('./templates/simple', { + // common render options to be passed to render functions + const commonRenderOptions = { applicationName: api.generator.pkg.name, applicationVersion: api.generator.pkg.version, applicationAndroidVersionCode: api.generator.pkg.version.split('.').join('0'), applicationDescription: api.generator.pkg.description || api.generator.pkg.name, applicationLicense: api.generator.pkg.license || 'MIT', applicationId: options.applicationId, - historyMode: options.historyMode || false, - }) + historyMode: options.historyMode, + doesCompile: api.hasPlugin('babel') || api.hasPlugin('typescript') ? true : false, + usingBabel: api.hasPlugin('babel') ? true : false, + usingTS: api.hasPlugin('typescript') ? true : false + }; + + console.log('adding to package.json'); + + api.extendPackage({ + nativescript: { + id: 'org.nativescript.application', + 'tns-ios': { + version: '5.2.0' + }, + 'tns-android': { + version: '5.2.1' + } + }, + scripts: { + 'build:android': 'npm run setup-webpack-config && tns build android --bundle --env.production && npm run remove-webpack-config', + 'build:ios': 'npm run setup-webpack-config && tns build ios --bundle --env.production && npm run remove-webpack-config', + 'remove-webpack-config': 'node ./node_modules/vue-cli-plugin-nativescript-vue/lib/scripts/webpack-maintenance post', + 'serve:android': 'npm run setup-webpack-config && tns run android --bundle --env.development', + 'serve:ios': 'npm run setup-webpack-config && tns run ios --bundle --env.development', + // 'inspect:android': 'npm run setup-webpack-config && vue inspect -- --env.android > out-android.js', + // 'inspect:ios': 'npm run setup-webpack-config && vue inspect -- --env.ios > out-ios.js', + 'debug:android': 'npm run setup-webpack-config && tns debug android --bundle --env.development', + 'debug:ios': 'npm run setup-webpack-config && tns debug ios --bundle --env.development', + 'preview:android': 'npm run setup-webpack-config && tns preview --bundle --env.development --env.android', + 'preview:ios': 'npm run setup-webpack-config && tns preview --bundle --env.development --env.ios', + 'setup-webpack-config': 'node ./node_modules/vue-cli-plugin-nativescript-vue/lib/scripts/webpack-maintenance pre', + 'clean:platforms': 'rimraf platforms', + 'clean:android': 'rimraf platforms/android', + 'clean:ios': 'rimraf platforms/ios' + }, + dependencies: { + 'nativescript-vue': '^2.0.2', + 'tns-core-modules': '^5.2.1' + }, + devDependencies: { + 'nativescript-dev-webpack': '^0.17.0', + 'nativescript-vue-template-compiler': '^2.0.2', + 'nativescript-worker-loader': '~0.9.1', + 'node-sass': '^4.11.0', + 'string-replace-loader': '^2.1.1', + rimraf: '^2.6.3', + webpack: '^4.29.6', + 'webpack-cli': '^3.2.3' + } + }); + + // add scripts when we are also developing for the web + if (!options.isNativeOnly) { + api.extendPackage({ + scripts: { + 'serve:web': 'vue-cli-service serve --mode development.web', + 'build:web': 'vue-cli-service build --mode production.web' + //'inspect:web': 'npm run setup-webpack-config && vue inspect -- --env.web > out-web.js' + } + }); + + // if we are using NativeScript-Vue-Web then add the package + if (options.templateType == 'nvw') { + api.extendPackage({ + dependencies: { + 'nativescript-vue-web': '^0.9.4' + } + }); + } + } else { + // + } + + if (api.hasPlugin('typescript')) { + api.extendPackage({ + dependencies: {}, + devDependencies: { + 'fork-ts-checker-webpack-plugin': '^0.4.15', + 'terser-webpack-plugin': '^1.2.3' + //'tns-platform-declarations': '^4.2.1' + } + }); + + // this means it's a typescript project and using babel + if (api.hasPlugin('babel')) { + api.extendPackage({ + dependencies: {}, + devDependencies: { + '@babel/types': '^7.1.3' + } + }); + } + } + + // if the project is using babel, then load appropriate packages + if (api.hasPlugin('babel')) { + api.extendPackage({ + devDependencies: { + '@babel/core': '^7.3.4', + '@babel/preset-env': '^7.3.4', + 'babel-loader': '^8.0.5', + '@babel/traverse': '^7.3.4' + } + }); + + api.render(async () => { + fs.ensureFileSync(genConfig.dirPathPrefix + 'babel.config.js'); + await applyBabelConfig(api, genConfig.dirPathPrefix + 'babel.config.js'); + }); + } + + // if the project is using eslint, add some global variables + // to the eslintConfig in order to avoid no-def errors + if (api.hasPlugin('eslint')) { + api.extendPackage({ + eslintConfig: { + globals: { + TNS_APP_MODE: true, + TNS_APP_PLATFORM: true + } + } + }); + } + + console.log('deleting from package.json'); + api.extendPackage((pkg) => { + // if the project is using babel, then delete babel-core + if (api.hasPlugin('babel')) { + delete pkg.devDependencies['babel-core']; + } + // we will be replacing these + delete pkg.scripts['serve'], delete pkg.scripts['build']; + + if (options.isNativeOnly) { + delete pkg.browserslist; + } - // delete the "public" directory - api.onCreateComplete(() => { - const publicPath = api.resolve('public') - if(fs.existsSync(publicPath)) { - rimraf.sync(publicPath) + if (options.templateType !== 'nvw') { + delete pkg.dependencies['nativescript-vue-web']; } - }) -} \ No newline at end of file + }); + + console.log('doing template rendering'); + + // render App_Resources folder + api.render(async () => { + // eslint-disable-next-line prettier/prettier + await renderDirectoryStructure( + api, + options, + rootOptions, + '.js', + commonRenderOptions, + './templates/App_Resources', + genConfig.dirPathPrefix + genConfig.appResourcesPathModifier + ); + }); + + // If Native only or Dual Native and Web Project. + if (!options.isNativeOnly) { + api.render(async () => { + // render src directory + await renderDirectoryStructure( + api, + options, + rootOptions, + genConfig.jsOrTs, + commonRenderOptions, + path.join('templates', genConfig.templateTypePathModifer, 'src'), + genConfig.dirPathPrefix + 'src' + ); + + // add router statements to src/main.*s + await vueRouterSetup(api, genConfig.dirPathPrefix, genConfig.jsOrTs); + + // add vuex statements to src/main.*s + await vuexSetup(api, options, genConfig.dirPathPrefix, genConfig.jsOrTs, genConfig.nativeAppPathModifier); + }); + } else { + // Is Native Only + api.render(async () => { + // render app directory + await renderDirectoryStructure( + api, + options, + rootOptions, + genConfig.jsOrTs, + commonRenderOptions, + path.join('templates', genConfig.templateTypePathModifer, 'src'), + genConfig.dirPathPrefix + genConfig.nativeAppPathModifier.slice(0, -1) + ); + + // add vuex statements to app/main.*s + await vuexSetup(api, options, genConfig.dirPathPrefix, genConfig.jsOrTs); + }); + } + + api.onCreateComplete(async () => { + // make changes to .gitignore + gitignoreAdditions(api); + + // create files in ./ or ./ns-example + writeRootFiles(api, options, genConfig.dirPathPrefix); + + // create nsconfig.json in ./ or ./ns-example + nsconfigSetup(genConfig.dirPathPrefix, api.resolve('nsconfig.json'), genConfig.nativeAppPathModifier, genConfig.appResourcesPathModifier); + + // copy over .vue with native.vue files + if (options.isNativeOnly) { + nativeOnlyRenameFiles(genConfig.dirPathPrefix + genConfig.nativeAppPathModifier.slice(0, -1)); + } + + // remove router config for projects that don't use vue-router + if (!rootOptions.router) { + fs.remove(genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'router' + genConfig.jsOrTs, (err) => { + if (err) throw err; + }); + } + + if (api.hasPlugin('typescript')) { + // we need to edit the tsconfig.json file in /app + // for a Native only project to remove references to /src + await tsconfigSetup(options, genConfig.dirPathPrefix, genConfig.nativeAppPathModifier); + + if (fs.existsSync(api.resolve('tslint.json'))) { + await tslintSetup(genConfig.dirPathPrefix, api.resolve('tslint.json'), genConfig.tsExclusionArray); + + const baseDir = genConfig.nativeAppPathModifier; + require('../lib/tslint')({ + '_': [`${baseDir}**/*.ts`, `${baseDir}**/*.vue`, `${baseDir}**/*.tsx`, 'tests/**/*.ts', 'tests/**/*.tsx'] + }, api, false); + } + } + + // the main difference between New and Existing for this section is + // that for New projects we are moving files around, but for + // existing projects we are copying files into ./ns-example + if (options.isNewProject) { + // move type files out of src to ./ or ./ns-example + if (api.hasPlugin('typescript')) { + // Do these synchronously so in the event we delete the ./src directory in a native only + // situation below we don't try and move a file that no longer exists + try { + fs.moveSync('./src/shims-tsx.d.ts', genConfig.dirPathPrefix + 'types/shims-tsx.d.ts', { overwrite: true }); + fs.moveSync('./src/shims-vue.d.ts', genConfig.dirPathPrefix + 'types/shims-vue.d.ts', { overwrite: true }); + } catch (err) { + throw err; + } + } + + // for new projects that are native only, move files/dirs and delete others + if (options.isNativeOnly) { + // Do these synchronously so that when we delete the ./src directory below + // we don't try and move a file that no longer exists + try { + // move store.js file from ./src to ./app + if (api.hasPlugin('vuex')) { + fs.moveSync('./src/store' + genConfig.jsOrTs, genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'store' + genConfig.jsOrTs, { + overwrite: true + }); + } + } catch (err) { + throw err; + } + // remove src directory as we don't need it any longer + fs.remove('./src', (err) => { + if (err) throw err; + }); + // remove public directory as we don't need it any longer + fs.remove('./public', (err) => { + if (err) throw err; + }); + // rename main.native.js to main.js + fs.moveSync( + genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'main.native' + genConfig.jsOrTs, + genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'main' + genConfig.jsOrTs, + { + overwrite: true + } + ); + + nativeOnlyPackageJsonSetup(genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'package.json'); + } + } else if (!options.isNewProject) { + // copy type files from ./src to ./ns-example + if (api.hasPlugin('typescript')) { + fs.copy('./src/shims-tsx.d.ts', path.join(genConfig.dirPathPrefix, 'types/shims-tsx.d.ts'), (err) => { + if (err) throw err; + }); + + fs.copy('./src/shims-vue.d.ts', path.join(genConfig.dirPathPrefix, 'types/shims-vue.d.ts'), (err) => { + if (err) throw err; + }); + } + + if (options.isNativeOnly) { + // move store.js file from ./src to ./ns-example/app + if (api.hasPlugin('vuex')) { + fs.copy('./src/store' + genConfig.jsOrTs, genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'store' + genConfig.jsOrTs, (err) => { + if (err) throw err; + }); + } + + // rename main.native.js to main.js + fs.moveSync( + genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'main.native' + genConfig.jsOrTs, + genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'main' + genConfig.jsOrTs, + { + overwrite: true + } + ); + + nativeOnlyPackageJsonSetup(genConfig.dirPathPrefix + genConfig.nativeAppPathModifier + 'package.json'); + } + } else { + // nothing to do here + } + }); +}; + +// setup vue-router options +// will not setup any vue-router options for native app +// for new projects it will write to changes as normal +// and for existing projects it will write changes to the ./ns-example directory +const vueRouterSetup = (module.exports.vueRouterSetup = async (api, filePathPrefix, jsOrTs) => { + try { + if (api.hasPlugin('vue-router')) { + api.injectImports(filePathPrefix.replace(/.\//, '') + 'src/main' + jsOrTs, `import router from './router';`); + api.injectRootOptions(filePathPrefix.replace(/.\//, '') + 'src/main' + jsOrTs, `router`); + } + } catch (err) { + throw err; + } +}); + +// setup Vuex options +// for new projects it will write to changes as normal +// and for existing projects it will write changes to the ./ns-example directory +const vuexSetup = (module.exports.vuexSetup = async (api, options, filePathPrefix, jsOrTs, nativeAppPathModifier) => { + try { + if (api.hasPlugin('vuex')) { + if (!options.isNativeOnly) { + api.injectImports(filePathPrefix.replace(/.\//, '') + 'src/main' + jsOrTs, `import store from './store';`); + api.injectRootOptions(filePathPrefix.replace(/.\//, '') + 'src/main' + jsOrTs, `store`); + + // if we're using Nativescript-Vue-Web, then we have to modify the main.native file + api.injectImports(filePathPrefix.replace(/.\//, '') + 'src/main.native' + jsOrTs, `import store from './store';`); + api.injectRootOptions(filePathPrefix.replace(/.\//, '') + 'src/main.native' + jsOrTs, `store`); + } else { + // if it's native only, it will not do anything in /src directory + api.injectImports(filePathPrefix.replace(/.\//, '') + nativeAppPathModifier + 'main' + jsOrTs, `import store from './store';`); + api.injectRootOptions(filePathPrefix.replace(/.\//, '') + nativeAppPathModifier + 'main' + jsOrTs, `store`); + } + } + } catch (err) { + throw err; + } +}); + +// write out babel.config.js options by adding options and replacing the base @vue/app +// for new projects it will write to the root of the project +// and for existing projects it will write it to the ./ns-example directory +const applyBabelConfig = (module.exports.applyBabelConfig = async (api, filePath) => { + const babelReplaceOptions = { + files: '', + from: " '@vue/app'", + to: " process.env.VUE_PLATFORM === 'web' ? '@vue/app' : {}, " + newline + " ['@babel/env', { targets: { esmodules: true } }]" + }; + + try { + babelReplaceOptions.files = filePath; + + api.render((files) => { + files[filePath] = api.genJSConfig({ + plugins: ['@babel/plugin-syntax-dynamic-import'], + presets: ['@vue/app'] + }); + // eslint-disable-next-line no-unused-vars + replace(babelReplaceOptions, (err, changes) => { + if (err) throw err; + }); + }); + } catch (err) { + throw err; + } +}); + +// write out files in the root of the project +// this includes the environment files as well as a global types file for +// Typescript projects. for new projects it will write files to the root of the project +// and for existing projects it will write it to the ./ns-example directory +const writeRootFiles = (module.exports.writeRootFiles = async (api, options, filePathPrefix) => { + try { + const envDevelopmentAndroid = 'NODE_ENV=development' + newline + 'VUE_APP_PLATFORM=android' + newline + 'VUE_APP_MODE=native'; + const envDevelopmentIOS = 'NODE_ENV=development' + newline + 'VUE_APP_PLATFORM=ios' + newline + 'VUE_APP_MODE=native'; + const envProductionAndroid = 'NODE_ENV=production' + newline + 'VUE_APP_PLATFORM=android' + newline + 'VUE_APP_MODE=native'; + const envProductionIOS = 'NODE_ENV=production' + newline + 'VUE_APP_PLATFORM=ios' + newline + 'VUE_APP_MODE=native'; + + fs.writeFileSync( + filePathPrefix + '.env.development.android', + envDevelopmentAndroid, + { + encoding: 'utf8' + }, + (err) => { + if (err) throw err; + } + ); + fs.writeFileSync( + filePathPrefix + '.env.development.ios', + envDevelopmentIOS, + { + encoding: 'utf8' + }, + (err) => { + if (err) throw err; + } + ); + fs.writeFileSync( + filePathPrefix + '.env.production.android', + envProductionAndroid, + { + encoding: 'utf8' + }, + (err) => { + if (err) throw err; + } + ); + fs.writeFileSync( + filePathPrefix + '.env.production.ios', + envProductionIOS, + { + encoding: 'utf8' + }, + (err) => { + if (err) throw err; + } + ); + + // only write these out if we are also developing for the web + if (!options.isNativeOnly) { + console.log('dual components env files'); + const envDevelopmentWeb = 'NODE_ENV=development' + newline + 'VUE_APP_PLATFORM=web' + newline + 'VUE_APP_MODE=web'; + const envProductionWeb = 'NODE_ENV=production' + newline + 'VUE_APP_PLATFORM=web' + newline + 'VUE_APP_MODE=web'; + + fs.writeFileSync( + filePathPrefix + '.env.development.web', + envDevelopmentWeb, + { + encoding: 'utf8' + }, + (err) => { + if (err) throw err; + } + ); + fs.writeFileSync( + filePathPrefix + '.env.production.web', + envProductionWeb, + { + encoding: 'utf8' + }, + (err) => { + if (err) throw err; + } + ); + } + + // only write this out if we are using typescript + if (api.hasPlugin('typescript')) { + // this file is ultimately optional if you don't use any process.env.VARIABLE_NAME references in your code + const globalTypes = + 'declare const TNS_ENV: string;' + newline + 'declare const TNS_APP_PLATFORM: string;' + newline + 'declare const TNS_APP_MODE: string;'; + fs.outputFileSync( + filePathPrefix + 'types/globals.d.ts', + globalTypes, + { + encoding: 'utf8' + }, + (err) => { + if (err) throw err; + } + ); + } + } catch (err) { + throw err; + } +}); + +// write .gitignore additions for native app exemptions +// will make changes to the root .gitignore file regardless of new or exisiting project +const gitignoreAdditions = (module.exports.gitignoreAdditions = async (api) => { + try { + let gitignoreContent; + const gitignorePath = api.resolve('.gitignore'); + const gitignoreAdditions = newline + '# NativeScript application' + newline + 'hooks' + newline + 'platforms' + newline + './webpack.config.js'; + + if (fs.existsSync(gitignorePath)) { + gitignoreContent = fs.readFileSync(gitignorePath, { + encoding: 'utf8' + }); + } else { + gitignoreContent = ''; + } + + if (gitignoreContent.indexOf(gitignoreAdditions) === -1) { + gitignoreContent += gitignoreAdditions; + + fs.writeFileSync( + gitignorePath, + gitignoreContent, + { + encoding: 'utf8' + }, + (err) => { + if (err) throw err; + } + ); + } + } catch (err) { + throw err; + } +}); + +// setup nsconfig.json file. for new projects it will write to the root of the project +// and for existing projects it will write it to the ./ns-example directory +const nsconfigSetup = (module.exports.nsconfigSetup = async (dirPathPrefix, nsconfigPath, nativeAppPathModifier, appResourcesPathModifier) => { + let nsconfigContent = ''; + + try { + if (fs.existsSync(nsconfigPath)) { + nsconfigContent = JSON.parse( + fs.readFileSync(nsconfigPath, { + encoding: 'utf8' + }) + ); + } else { + nsconfigContent = {}; + } + + nsconfigContent.appPath = nativeAppPathModifier.slice(0, -1); + nsconfigContent.appResourcesPath = appResourcesPathModifier; + + fs.writeFileSync( + dirPathPrefix + 'nsconfig.json', + JSON.stringify(nsconfigContent, null, 2), + { + encoding: 'utf8' + }, + (err) => { + if (err) console.error(err); + } + ); + } catch (err) { + throw err; + } +}); + +// can be used to strip out template tags in native only project +// currently unused in preference for EJS templating +// eslint-disable-next-line no-unused-vars +const stripTemplateTags = (module.exports.stripTemplateTags = async (srcPathPrefix) => { + try { + const files = await getAllFilesInDirStructure(srcPathPrefix, ''); + + for (const file of files) { + if (file.slice(-4) == '.vue') { + const options = { + files: path.join(srcPathPrefix, file), + from: [ + new RegExp(`^(()[\\s\\S]*?(<\\/template>)`, `gim`), + new RegExp(`^(()`, `gim`) + ], + to: ['', '