未应用Nativescript 5.0 Webpack Platform特定的CSS样式

时间:2018-11-12 11:20:13

标签: webpack nativescript nativescript-angular

在带有角度的NS 5应用程序中,我正在使用特定于平台的css文件根据运行它的设备对应用程序进行样式设置。我有4个档案-     phone.android.css, phone.ios.css, tablet.android.css and tablet.ios.css存储在app文件夹中。

当我使用     tns run ios 我发现该应用程序运行并且样式正确应用。但是当我使用     tns run ios --bundle。 完全不应用css样式。

关于如何在特定平台的css文件中获取css样式以正确应用的任何建议。升级到NS 5和Nativescript-dev-webpack 0.17.0之前,即使使用bundle标志,所有样式都可以正常工作

Package.JSON

{
  "android": {
    "markingMode": "none"
  },
  "description": "NativeScript Application",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "org.nativescript.abc",
    "tns-android": {
      "version": "5.0.0"
    },
    "tns-ios": {
      "version": "5.0.0"
    }
  },
  "dependencies": {
    "@angular/animations": "~6.1.0",
    "@angular/common": "~6.1.0",
    "@angular/compiler": "~6.1.0",
    "@angular/core": "~6.1.0",
    "@angular/forms": "~6.1.0",
    "@angular/http": "~6.1.0",
    "@angular/platform-browser": "~6.1.0",
    "@angular/platform-browser-dynamic": "~6.1.0",
    "@angular/router": "~6.1.0",
    "nativescript-algolia": "^1.1.0",
    "nativescript-angular": "^6.2.0",
    "nativescript-camera": "^4.0.2",
    "nativescript-email": "^1.5.3",
    "nativescript-filter-select": "^1.2.9",
    "nativescript-filterable-listpicker": "^2.2.3",
    "nativescript-geolocation": "^4.2.6",
    "nativescript-imagepicker": "^6.0.4",
    "nativescript-iqkeyboardmanager": "^1.3.0",
    "nativescript-ngx-slides": "^6.1.0",
    "nativescript-pdf-view": "^2.0.1",
    "nativescript-plugin-firebase": "^7.3.0",
    "nativescript-social-share": "^1.5.0",
    "nativescript-theme-core": "~1.0.4",
    "nativescript-toast": "^1.4.6",
    "nativescript-ui-listview": "^3.8.0",
    "nativescript-web-image-cache": "^4.2.2",
    "reflect-metadata": "~0.1.8",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.2.2",
    "tns-core-modules": "^5.0.2"
  },
  "devDependencies": {
    "@angular/compiler-cli": "~6.1.0",
    "@ngtools/webpack": "~6.2.0",
    "babel-traverse": "6.26.0",
    "babel-types": "6.26.0",
    "babylon": "6.18.0",
    "codelyzer": "^4.4.4",
    "es6-promise-loader": "^1.0.2",
    "lazy": "1.0.11",
    "nativescript-dev-typescript": "^0.7.3",
    "nativescript-dev-webpack": "^0.17.0",
    "prettier": "^1.11.1",
    "tslint": "^5.1.0",
    "typescript": "~2.7.2",
    "webpack": "^4.25.1",
    "zone.js": "^0.8.26"
  }
}

webpack.config.js文件

const { join, relative, resolve, sep } = require("path");

const webpack = require("webpack");
const nsWebpack = require("nativescript-dev-webpack");
const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target");
const { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const { AngularCompilerPlugin } = require("@ngtools/webpack");

module.exports = env => {
    // Add your custom Activities, Services and other Android app components here.
    const appComponents = [
        "tns-core-modules/ui/frame",
        "tns-core-modules/ui/frame/activity",
    ];

    const platform = env && (env.android && "android" || env.ios && "ios");
    if (!platform) {
        throw new Error("You need to provide a target platform!");
    }

    const projectRoot = __dirname;

    // Default destination inside platforms/<platform>/...
    const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));
    const appResourcesPlatformDir = platform === "android" ? "Android" : "iOS";

    const {
        // The 'appPath' and 'appResourcesPath' values are fetched from
        // the nsconfig.json configuration file
        // when bundling with `tns run android|ios --bundle`.
        appPath = "app",
        appResourcesPath = "app/App_Resources",

        // You can provide the following flags when running 'tns run android|ios'
        aot, // --env.aot
        snapshot, // --env.snapshot
        uglify, // --env.uglify
        report, // --env.report
        sourceMap, // --env.sourceMap
        hmr, // --env.hmr,
    } = env;
    const externals = (env.externals || []).map((e) => { // --env.externals
        return new RegExp(e + ".*");
    });

    const appFullPath = resolve(projectRoot, appPath);
    const appResourcesFullPath = resolve(projectRoot, appResourcesPath);

    const entryModule = `${nsWebpack.getEntryModule(appFullPath)}.ts`;
    const entryPath = `.${sep}${entryModule}`;

    const ngCompilerPlugin = new AngularCompilerPlugin({
        hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),
        platformTransformers: aot ? [nsReplaceBootstrap(() => ngCompilerPlugin)] : null,
        mainPath: resolve(appPath, entryModule),
        tsConfigPath: join(__dirname, "tsconfig.tns.json"),
        skipCodeGeneration: !aot,
        sourceMap: !!sourceMap,
    });

    const config = {
        mode: uglify ? "production" : "development",
        context: appFullPath,
        externals,
        watchOptions: {
            ignored: [
                appResourcesFullPath,
                // Don't watch hidden files
                "**/.*",
            ]
        },
        target: nativescriptTarget,
        entry: {
            bundle: entryPath,
        },
        output: {
            pathinfo: false,
            path: dist,
            libraryTarget: "commonjs2",
            filename: "[name].js",
            globalObject: "global",
        },
        resolve: {
            extensions: [".ts", ".js", ".scss", ".css"],
            // Resolve {N} system modules from tns-core-modules
            modules: [
                resolve(__dirname, "node_modules/tns-core-modules"),
                resolve(__dirname, "node_modules"),
                "node_modules/tns-core-modules",
                "node_modules",
            ],
            alias: {
                '~': appFullPath
            },
            symlinks: true
        },
        resolveLoader: {
            symlinks: false
        },
        node: {
            // Disable node shims that conflict with NativeScript
            "http": false,
            "timers": false,
            "setImmediate": false,
            "fs": "empty",
            "__dirname": false,
        },
        devtool: sourceMap ? "inline-source-map" : "none",
        optimization: {
            splitChunks: {
                cacheGroups: {
                    vendor: {
                        name: "vendor",
                        chunks: "all",
                        test: (module, chunks) => {
                            const moduleName = module.nameForCondition ? module.nameForCondition() : '';
                            return /[\\/]node_modules[\\/]/.test(moduleName) ||
                                appComponents.some(comp => comp === moduleName);
                        },
                        enforce: true,
                    },
                }
            },
            minimize: !!uglify,
            minimizer: [
                new UglifyJsPlugin({
                    parallel: true,
                    cache: true,
                    uglifyOptions: {
                        output: {
                            comments: false,
                        },
                        compress: {
                            // The Android SBG has problems parsing the output
                            // when these options are enabled
                            'collapse_vars': platform !== "android",
                            sequences: platform !== "android",
                        }
                    }
                })
            ],
        },
        module: {
            rules: [
                {
                    test: new RegExp(entryPath),
                    use: [
                        // Require all Android app components
                        platform === "android" && {
                            loader: "nativescript-dev-webpack/android-app-components-loader",
                            options: { modules: appComponents }
                        },

                        {
                            loader: "nativescript-dev-webpack/bundle-config-loader",
                            options: {
                                angular: true,
                                loadCss: !snapshot, // load the application css if in debug mode
                            }
                        },
                    ].filter(loader => !!loader)
                },

                { test: /\.html$|\.xml$/, use: "raw-loader" },

                // tns-core-modules reads the app.css and its imports using css-loader
                {
                    test: /[\/|\\]app\.css$/,
                    use: {
                        loader: "css-loader",
                        options: { minimize: false, url: false },
                    }
                },
                {
                    test: /[\/|\\]app\.scss$/,
                    use: [
                        { loader: "css-loader", options: { minimize: false, url: false } },
                        "sass-loader"
                    ]
                },

                // Angular components reference css files and their imports using raw-loader
                { test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: "raw-loader" },
                { test: /\.scss$/, exclude: /[\/|\\]app\.scss$/, use: ["raw-loader", "resolve-url-loader", "sass-loader"] },

                {
                    test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
                    use: [
                        "nativescript-dev-webpack/moduleid-compat-loader",
                        "@ngtools/webpack",
                    ]
                },

                // Mark files inside `@angular/core` as using SystemJS style dynamic imports.
                // Removing this will cause deprecation warnings to appear.
                {
                    test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
                    parser: { system: true },
                },
            ],
        },
        plugins: [
            // Define useful constants like TNS_WEBPACK
            new webpack.DefinePlugin({
                "global.TNS_WEBPACK": "true",
                "process": undefined,
            }),
            // Remove all files from the out dir.
            new CleanWebpackPlugin([`${dist}/**/*`]),
            // Copy native app resources to out dir.
            new CopyWebpackPlugin([
                {
                    from: `${appResourcesFullPath}/${appResourcesPlatformDir}`,
                    to: `${dist}/App_Resources/${appResourcesPlatformDir}`,
                    context: projectRoot
                },
            ]),
            // Copy assets to out dir. Add your own globs as needed.
            new CopyWebpackPlugin([
                { from: "App_Resources/**" },
                { from: "fonts/**" },
                { from: "**/*.jpg" },
                { from: "**/*.png" },
                { from: "**/*.xml" },
                { from: "**/*.css" },
            ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
            // Generate a bundle starter script and activate it in package.json
            new nsWebpack.GenerateBundleStarterPlugin([
                "./vendor",
                "./bundle",
            ]),
            // For instructions on how to set up workers with webpack
            // check out https://github.com/nativescript/worker-loader
            new NativeScriptWorkerPlugin(),
            ngCompilerPlugin,
            // Does IPC communication with the {N} CLI to notify events when running in watch mode.
            new nsWebpack.WatchStateLoggerPlugin(),
        ],
    };


    if (report) {
        // Generate report files for bundles content
        config.plugins.push(new BundleAnalyzerPlugin({
            analyzerMode: "static",
            openAnalyzer: false,
            generateStatsFile: true,
            reportFilename: resolve(projectRoot, "report", `report.html`),
            statsFilename: resolve(projectRoot, "report", `stats.json`),
        }));
    }

    if (snapshot) {
        config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({
            chunk: "vendor",
            angular: true,
            requireModules: [
                "reflect-metadata",
                "@angular/platform-browser",
                "@angular/core",
                "@angular/common",
                "@angular/router",
                "nativescript-angular/platform-static",
                "nativescript-angular/router",
            ],
            projectRoot,
            webpackConfig: config,
        }));
    }

    if (hmr) {
        config.plugins.push(new webpack.HotModuleReplacementPlugin());
    }

    return config;
};

1 个答案:

答案 0 :(得分:0)

您应导入文件名中未指定平台的样式。

例如导入phone.css而不是phone.ios.css等。

在构建过程中,.ios / .android将自动添加,具体取决于您要构建的平台。

尽管您的帖子内容不清楚,但在您的评论中您提到了导入phone.ios.css,由于您的iOS应用正确加载了样式,因此问题得到了进一步的确认,而问题仅在于Android。

关于包-这是由于webpack最有可能在构建过程中使用,以上内容应为您解决。

P.S。 OP已经有将近一年的时间了,很可能找到了解决方案-但问题尚未得到解答。

OP,下次找到解决方案时,如果您自行发布解决方案:)