Ng2-translate与Webpack不兼容 [英] Ng2-translate incompatible with webpack

查看:75
本文介绍了Ng2-translate与Webpack不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家早上好. 我在我的应用程序中使用ng2-translate插件,运行tns run ios效果很好. 但是,当使用命令tns运行ios --bundle --env.uglify --env.aot时,Webpack会进行复制而不会给出任何错误,但是打开时会出现错误应用程序:

Good morning guys. I'm using the ng2-translate plugin in my application, running tns run ios works perfectly. But when running with the command tns run ios --bundle --env.uglify --env.aot the webpack does the copying without giving any error, but the error app when opening:

CONSOLE LOG file:///app/vendor.js:1:1200993:
CONSOLE ERROR file:///app/vendor.js:1:28276: ERROR TypeError: this.http.get(this.prefix+"/"+e+this.suffix).map is not a function. (In 'this.http.get(this.prefix+"/"+e+this.suffix).map(function(e){return e.json()})', 'this.http.get(this.prefix+"/"+e+this.suffix).map' is undefined)
CONSOLE ERROR file:///app/vendor.js:1:1125775: bootstrap: ERROR BOOTSTRAPPING ANGULAR
CONSOLE ERROR file:///app/vendor.js:1:1125775: bootstrap: this.http.get(this.prefix+"/"+e+this.suffix).map is not a function. (In 'this.http.get(this.prefix+"/"+e+this.suffix).map(function(e){return e.json()})', 'this.http.get(this.prefix+"/"+e+this.suffix).map' is undefined)
getTranslation@file:///app/vendor.js:1:886381
getTranslation@file:///app/vendor.js:1:887491
retrieveTranslations@file:///app/vendor.js:1:887380
setDefaultLang@file:///app/vendor.js:1:886824
n@file:///app/bundle.js:1:88782
ka@file:///app/vendor.js:1:110925

以前有人遇到过这个问题吗?

Has anyone had this problem before?

我已经使用本机脚本测试了该插件: https://www.npmjs. com/package/@ ngx-translate/core ,但我没有成功.

I already tested this plugin with nativescript: https://www.npmjs.com/package/@ngx-translate/core but I did not succeed.

推荐答案

是的,它已添加到webpack中,这是我当前的配置:

Yes it is added in the webpack, this is my current 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 { 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
} = env;

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,
    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({
                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: {
                            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: "fonts/**" },
            { from: 'styles/css/**' },
            { from: "assets/i18n/*.json"},
            { from: "**/*.jpg" },
            { from: "**/*.png" },
        ], { 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,
    }));
}

return config;

};

这篇关于Ng2-translate与Webpack不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆