使用 Webpack 将多个 javascript 文件压缩并缩小为一个文件? [英] Compress and Minify multiples javascript files into one, with Webpack?

查看:47
本文介绍了使用 Webpack 将多个 javascript 文件压缩并缩小为一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 webpack 将多个 javascript 文件连接起来,将其缩小为一个.

I'm trying to concatenate, minify multiples javascript files into one, with webpack.

所以我的问题可以用 webpack 来完成吗?如何?

So my question can this be done with webpack? and How?

我尝试了很多方法,但无法让它按我想要的方式工作.

I tried a lot of ways, but couldn't get it to work as what I wanted.

我最好展示一些例子.

3 个 JavaScript 文件.

3 javascript files.

app.js

var fnA = function () {
    console.log('fnA')
}

global.js

fnA();

ma​​in.js

require('./app.js');
require('./global.js');

webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry : [
        './app/main.js'
    ],
    output : {
        path : path.resolve(__dirname, 'dist'),
        filename : 'bundle.js'
    },
    plugins : [
        new webpack.optimize.UglifyJsPlugin(
        {
            minimize: true,
            compress: false,
            mangle: {
                 keep_fnames: true
            },
            bare_returns : true
        }),
    ]
};

我希望 global.js 能够调用 app.js 中的任何函数.可能这可以用 grunt 来完成,但我认为 webpack 也可以做到这一点.

I'm expecting that global.js is able to call to any function in app.js. Probably this can be done with grunt, but I thought webpack can do this too.

担心我走向完全错误的方向.谷歌一下,但似乎找不到任何解决方案,尝试使用其他插件如块,这没有帮助.

Worry that I'm heading to a total wrong direction. Google around, but can't seem to find any solution, tried with other plugin suc as chunk, which doesn't helps.

欢迎任何建议.提前致谢.

Any advices are welcome. Thanks in advance.

推荐答案

我把一些简单的东西放在一起,但你需要 babel.

I put together something simple but you need babel.

https://github.com/vpanjganj/simple-webpack-sample

这是你的 webpack 配置:

This is your webpack config:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: [ "./app/main.js" ],
    output: {
        path: path.join(__dirname, "./dist"),
        filename: "bundle.js"
    },

  module: {
    rules: [
      { test: /\.js$/, use: [ { loader: 'babel-loader' } ], exclude: /node_modules/ }
    ]
  },

  plugins: [
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ]
};

这里是您的 2 个模块:

here your 2 modules:

第一个模块,moduleOne.js:

export default function sayHello() {
   console.log('hello')
}

moduleTwo.js 文件:

export default function sayBye() {
   console.log('bye')
}

和你的 main.js 文件:

import sayHello from './moduleOne'
import sayBye from './moduleTwo'

const myApp = ()=>{
   sayHello();
   sayBye()
};

myApp();

构建命令:

$ ./node_modules/.bin/webpack  --color --display-error-details --config ./webpack.js"

这篇关于使用 Webpack 将多个 javascript 文件压缩并缩小为一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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