如何使用不同的Webpack配置创建2个不同的javascript文件?

时间:2019-06-27 18:04:00

标签: javascript webpack babel

我需要创建2个不同的JavaScript和CSS文件,一个最小化,而另一个则不。

我只希望在Chrome中呈现未最小化的文件,对于其他浏览器,我需要常规的最小化和压缩代码。

我尝试过使用预置环境,更改.babelrc文件,甚至尝试使用浏览器列表。

webpack.dev.js

    private Context mContext;
    private String email, username, password1, password2, trainerCode, description, imageUrl = Finals.DEFAULT_USER_IMAGE_URL;
    private EditText mEmail, mPassword1, mPassword2, mUsername, mTrainerCode, mDescription;
    private Button btnSubmit, btnBack;
    private ImageView imageView;
    private ProgressDialog pDialog;
    private String userID;
    private boolean isTrainer, imagePressed = false;
    private Uri filePath;

    //firebase
    private FirebaseAuth mAuth;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
    private FirebaseStorage storage;
    private StorageReference storageReference;


    private View.OnClickListener imageClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            imagePressed = true;
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), Finals.PICK_IMAGE_REQUEST);

        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        mContext = SignUpActivity.this;
        pDialog = new ProgressDialog(this);

        mEmail = findViewById(R.id.userEmail);
        mUsername = findViewById(R.id.userName);
        btnSubmit = findViewById(R.id.btn_submit);
        mPassword1 = findViewById(R.id.userPassword1);
        mPassword2 = findViewById(R.id.userPassword2);
        mTrainerCode = findViewById(R.id.userCode);
        mDescription = findViewById(R.id.userDescription);
        imageView = findViewById(R.id.userImageAdd);
        btnBack = findViewById(R.id.backBtn);

        btnSubmit.setOnClickListener(btnSubmitListener);
        imageView.setOnClickListener(imageClickListener);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();
        storage = FirebaseStorage.getInstance();
        storageReference = storage.getReference();
    }

    private View.OnClickListener btnSubmitListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            email = mEmail.getText().toString();
            username = mUsername.getText().toString();
            password1 = mPassword1.getText().toString();
            password2 = mPassword2.getText().toString();
            trainerCode = mTrainerCode.getText().toString();
            description = mDescription.getText().toString();
            isTrainer = false;

            if (checkInputs(email, username, password1, password2, trainerCode)) {
                pDialog.setMessage("Creating User...");
                pDialog.show();
                if (imagePressed && filePath != null)
                    uploadImage();
                else
                    registerNewUser();
            }
        }
    };

    private void uploadImage() {
        final StorageReference ref = storageReference.child("users/" + UUID.randomUUID().toString());
        ref.putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()){
                    throw task.getException();
                }
                return ref.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                Uri downUri = task.getResult();
                imageUrl = downUri.toString();
                registerNewUser();
            }
        });
    }


    public void registerNewUser() {
        mAuth.createUserWithEmailAndPassword(email, password1)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful()) {
                            Toast.makeText(SignUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();

                        } else {
                            userID = mAuth.getCurrentUser().getUid();
                            addNewUser();
                        }

                    }
                });
    }

    private boolean checkInputs(String email, String name, String password1, String password2, String trainerCode) {
        if (email.equals("")) {
            Toast.makeText(mContext, "Please enter email", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (name.equals("")) {
            Toast.makeText(mContext, "Please enter name", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (password1.equals("")) {
            Toast.makeText(mContext, "Please enter password", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (password2.equals("")) {
            Toast.makeText(mContext, "Please repeat password", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!password1.equals(password2)) {
            Toast.makeText(mContext, "Passwords don't natch", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!trainerCode.equals("")) {
            if (trainerCode.equals(Finals.T_CODE)) {
                isTrainer = true;
                return true;
            } else {
                Toast.makeText(mContext, "Not a real trainer code!", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    public void addNewUser() {

        UserClass user = new UserClass(description, email, userID, imageUrl, isTrainer, username, password1);

        myRef.child("users").child(userID).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    pDialog.dismiss();
                    Toast.makeText(mContext, "Created new User", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(SignUpActivity.this, MainActivity.class));
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Finals.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                && data != null && data.getData() != null) {
            filePath = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

.babelrc

const merge = require('webpack-merge');
const loaders = require('./webpack.loaders');
const plugins = require('./webpack.plugins');

const common = merge([{
    mode: 'development',
    entry: {
        main: [
            './src/main/resources/js/index.js'
        ],
        sitemap: [
            './src/main/resources/js/indexSiteMap.js'
        ],
        error: [
            './src/main/resources/js/error/error.js'
        ],
        icons: [
            './src/main/resources/js/fonts/google.js',
            './src/main/resources/js/fonts/features.font.js',
            './src/main/resources/js/fonts/generals.font.js'
        ]
    },
    output: {
        filename: '[name].js',
        chunkFilename: '[name].js'
    },
    devtool: 'source-map',
    optimization: {
        splitChunks: {
            cacheGroups: {
                libs: {
                    test: /node_modules/,
                    name: "libs",
                    chunks: "initial",
                    enforce: true
                }
            }
        }
    }
},
loaders.loadSass(),
loaders.loadHandlebars(),
loaders.loadReact(),
loaders.loadFileLoader(false),
loaders.loadFonts(false),
loaders.loadExpose(),
loaders.loadEslint(),
]);

module.exports = () => {
    return merge([
        common,
        plugins.clean(),
        plugins.extractCSS(false),
        plugins.copy()
    ]);
}

我得到了两个不同的JavaScript文件,common.js和modern.js

我将在chrome中加载现代的-不是最小化文件-否则,我将使用common.js文件

1 个答案:

答案 0 :(得分:0)

您将需要2个不同的Webpack配置,并传递如下所示的命令行参数:

webpack --env.browser=chrome --open 'Google Chrome'

webpack --env.browser=other --open safari

并在webpack.chrome.jswebpack.other.js中维护2个不同的Webpack配置

并将其放入webpack.config.js

module.exports = env => require(`./webpack.${env}.js`);

您还需要在不同的端口中运行2个不同的本地服务器或webpack-dev-server配置,如下所示:

webpack.chrome.js

  mode: 'production',
  devServer: {
    compress: true,
    contentBase: path.join(__dirname, './dist'),
    port: 9000,
  },

webpack.other.js

  mode: 'development',
  devServer: {
    contentBase: path.join(__dirname, './dist'),
    port: 9001,
  },