NativeScript / nativescript-dev-webpack

A package to help with webpacking NativeScript apps.
Apache License 2.0
97 stars 49 forks source link

class extend & env.snapshot => Exception in thread "main" java.io.IOException: File already exists. This may lead to undesired behavior. #580

Open des-esseintes opened 6 years ago

des-esseintes commented 6 years ago

Hello!

Issue Checklist

Tell us about the problem

I'm having a service and a receiver described in AndroidManifest.xml, and a couple of js files extending the classes (all taken from nativescript background services example working w/ android's alarmManager). everything seems to be fine when using no webpack or just plain webpack, but goes out of control w/ snapshot generation:

Project successfully prepared (Android)
Executing after-prepare hook from /home/k/dev/android/smokealarm/hooks/after-prepare/nativescript-dev-webpack.js
mv: './snapshot.blob' и 'snapshot.blob' - один и тот же файл
mv: './snapshot.blob' и 'snapshot.blob' - один и тот же файл
mv: './snapshot.blob' и 'snapshot.blob' - один и тот же файл
Building project...
Gradle build...
     + applying user-defined configuration from /home/k/dev/android/smokealarm/app/App_Resources/Android/app.gradle
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
Configuration 'debugCompile' in project ':app' is deprecated. Use 'debugImplementation' instead.
     + adding nativescript runtime package dependency: nativescript-optimized
     + adding aar plugin dependency: /home/k/dev/android/smokealarm/node_modules/nativescript-android-utils/platforms/android/androidutils.aar
     + adding aar plugin dependency: /home/k/dev/android/smokealarm/node_modules/nativescript-local-notifications/platforms/android/localnotlib-release.aar
     + adding aar plugin dependency: /home/k/dev/android/smokealarm/node_modules/tns-core-modules-widgets/platforms/android/widgets-release.aar
Gradle build...
     + applying user-defined configuration from /home/k/dev/android/smokealarm/app/App_Resources/Android/app.gradle
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
Configuration 'debugCompile' in project ':app' is deprecated. Use 'debugImplementation' instead.
     + adding nativescript runtime package dependency: nativescript-optimized
     + adding aar plugin dependency: /home/k/dev/android/smokealarm/node_modules/nativescript-android-utils/platforms/android/androidutils.aar
     + adding aar plugin dependency: /home/k/dev/android/smokealarm/node_modules/nativescript-local-notifications/platforms/android/localnotlib-release.aar
     + adding aar plugin dependency: /home/k/dev/android/smokealarm/node_modules/tns-core-modules-widgets/platforms/android/widgets-release.aar
Warning: there already is an extend called com.tns.broadcastreceivers.NotificationEventReceiver.
Warning: The static binding generator will generate extend from:bundle.js implementation
Warning: there already is an extend called com.tns.notifications.NotificationIntentService.
Warning: The static binding generator will generate extend from:bundle.js implementation
Warning: there already is an extend called com.tns.broadcastreceivers.NotificationServiceStarterReceiver.
Warning: The static binding generator will generate extend from:bundle.js implementation
Exception in thread "main" java.io.IOException: File already exists. This may lead to undesired behavior.
Please change the name of one of the extended classes.
File:/home/k/dev/android/smokealarm/platforms/android/app/src/main/java/com/tns/broadcastreceivers/NotificationEventReceiver.java Class: com.tns.broadcastreceivers.NotificationEventReceiver
    at org.nativescript.staticbindinggenerator.Generator.writeBindings(Generator.java:65)
    at org.nativescript.staticbindinggenerator.Main.main(Main.java:48)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:runSbg'.
> Process 'command '/opt/icedtea-bin-3.5.1/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s
Command ./gradlew failed with exit code 1

Local environment

Project data

- [x] Webpack configuration:

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 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");

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", resolve(dirname, "app/notifications/NotificationEventReceiver"), resolve(dirname, "app/notifications/NotificationIntentService"), resolve(__dirname, "app/notifications/NotificationServiceStarterReceiver"), ];

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

const platforms = ["ios", "android"];
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'
    snapshot, // --env.snapshot
    uglify, // --env.uglify
    report, // --env.report
} = env;

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

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

const config = {
    mode: uglify ? "production" : "development",
    context: appFullPath,
    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: [".js", ".scss", ".css"],
        // Resolve {N} system modules from tns-core-modules
        modules: [
            "node_modules/tns-core-modules",
            "node_modules",
        ],
        alias: {
            '~': appFullPath
        },
        // don't resolve symlinks to symlinked modules
        symlinks: false
    },
    resolveLoader: {
        // don't resolve symlinks to symlinked loaders
        symlinks: false
    },
    node: {
        // Disable node shims that conflict with NativeScript
        "http": false,
        "timers": false,
        "setImmediate": false,
        "fs": "empty",
        "__dirname": false,
    },
    devtool: "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({
                uglifyOptions: {
                    parallel: true,
                    cache: true,
                    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: {
                            loadCss: !snapshot, // load the application css if in debug mode
                        }
                    },
                ].filter(loader => !!loader)
            },

            { test: /\.(html|xml)$/, use: "nativescript-dev-webpack/xml-namespace-loader"},

            {
                test: /\.css$/,
                use: { loader: "css-loader", options: { minimize: false, url: false } }
            },

            {
                test: /\.scss$/,
                use: [
                    { loader: "css-loader", options: { minimize: false, url: false } },
                    "sass-loader"
                ]
            }
        ]
    },
    plugins: [
        // Define useful constants like TNS_WEBPACK
        new webpack.DefinePlugin({
            "global.TNS_WEBPACK": "true",
        }),
        // 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: "fonts/**" },
            { from: "**/*.jpg" },
            { from: "**/*.png" },
            { from: "alarm.db" },
            { from: "sound/*mp3" },
        ], { 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(),
        new nsWebpack.PlatformFSPlugin({
            platform,
            platforms,
        }),
        // 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",
        requireModules: [
            "tns-core-modules/bundle-entry-points",
        ],
        projectRoot,
        webpackConfig: config,
    }));
}

return config;

};

yahyaKacem commented 4 years ago

Hi, I'm having the same error when building with the snapshot flag on, getting this error:

Error executing Static Binding Generator: File already exists. This may lead to undesired behavior. Please change the name of one of the extended classes. File:/path/to/project/platforms/android/app/src/main/java/com/tns/NotificationEventReceiver.java Class: com.tns.NotificationEventReceiver Detailed log here: /path/to/project/platforms/android/build-tools/runSbg.log

the content of the log file /path/to/project/platforms/android/build-tools/runSbg.log:

Warning: there already is an extend called com.tns.NotificationEventReceiver.
Warning: The static binding generator will generate extend from:1.js implementation
Warning: there already is an extend called com.tns.NotificationIntentService.
Warning: The static binding generator will generate extend from:1.js implementation
java.io.IOException: File already exists. This may lead to undesired behavior.
Please change the name of one of the extended classes.
File:/path/to/project/platforms/android/app/src/main/java/com/tns/NotificationEventReceiver.java Class: com.tns.NotificationEventReceiver
    at org.nativescript.staticbindinggenerator.Generator.writeBindings(Generator.java:112)
    at org.nativescript.staticbindinggenerator.Main.main(Main.java:55)

I run this command: tns build android --release --env.uglify --env.aot --env.snapshot --key-store-path 'keystore-file-path.ext' --key-store-password 'password' --key-store-alias 'Alias' --key-store-alias-password 'aliasPassword' --copy-to './' --bundle the build pass without the snapshot flag without errors.

Platform Mac os Catalina 10.15.2 Node version: 12.8.1 NativeScript CLI version 6.3.0

kanclalg commented 4 years ago

I'm having the same issue. Have any of you found a solution?

rosen-vladimirov commented 4 years ago

Hey guys, Can you please send a package.json and ideally a sample application reproducing the issue. It seems some of the plugins or your local code conflicts with extending the same class multiple times which leads to the error. We cannot determine the cause without more information on this case as the problem seems related to the application itself or the usage of specific plugins.