Chrillewoodz
Chrillewoodz

Reputation: 28338

NativeScript/Angular - How to share imports between the two applications?

I can't believe this isn't mentioned anywhere on the internet nor in the official NativeScript docs.

How do you share imports between a web app and a native app?

The following works when running the app in a native environment with npm run android:

import {App} from '~/app/shared/constants/app.constant';

But then if I run it with ng serve to run my app in the browser it says

Cannot find module '~/app/shared/constants/app.constant'.

If I try to define custom paths in my tsconfig.json:

"paths": {
    "~/*": [
        "src/*"
    ],
    "*": [
        "./node_modules/tns-core-modules/*",
        "./node_modules/*"
    ],
    "@components/*": ["src/app/shared/components/*"],
    "@constants/*": ["src/app/shared/constants/*"]
}

And then doing:

import {App} from '@constants/app.constant';

Running this with ng serve works but GUESS WHAT, it doesn't work when running the app with npm run android.

You can't check which platform you're running in either and decide how the imports look because then you get "duplicate imports" error due to the same thing being imported twice in the same file.

Can someone please help me before I go insane?

EDIT:

I ran this command to generate the project:

ng new -c=@nativescript/schematics foo-project --shared --style=scss

As described here.

This is the tsconfig.json:

{
    "compileOnSave": false,
    "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es2017",
            "dom",
            "es6",
            "es2015.iterable"
        ],
        "baseUrl": ".",
        "paths": {
            "~/*": [
                "src/*"
            ],
            "*": [
                "./node_modules/tns-core-modules/*",
                "./node_modules/*"
            ],
            "@components/*": ["src/app/shared/components/*"],
            "@constants/*": ["src/app/shared/constants/*"]
        }
    },
    "exclude": [
        "**/*.tns.ts",
        "**/*.android.ts",
        "**/*.ios.ts",
        "**/*.spec.ts"
    ]
}

Upvotes: 0

Views: 315

Answers (0)

Related Questions