Alvaro
Alvaro

Reputation: 41595

Bundle JS files with webpack scripts?

I'm super new to webpack and I do not seem to find a way to bundle JS files as I did with Gulp in a very easy way. I've been searching a bit but didn't find any straight answer to it.

Right now I'm creating two minified files by using in my package.json file, but I would love to have a single one instead:

"scripts": {
    "stand-alone": "concurrently 'webpack --config=webpack.config.js src/whatever.vue demos/build.min.js --output-library=whatever1'  'webpack --config=webpack.config.js src/whatever2.js demos/mixin.min.js --output-library=whatever2'",
},

Then my webpack.config.js looks like this:

const webpack = require('webpack');

module.exports = {
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.js'
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            scss: 'vue-style-loader!css-loader!sass-loader',
            js: 'babel-loader'
          }
        }
      },
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
        }
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        drop_console: false,
      }
    })
  ],
};

Upvotes: 7

Views: 21284

Answers (1)

Ricky Ruiz
Ricky Ruiz

Reputation: 26751

I believe you are looking for entry points.

In your webpack.config.js module exports object:

Define the entry property:

 entry: {
    app: ['./path/to/file.js', './path/to/file2.js'],
  },

Define the output property:

 output: {
   path: '/path/to/assets', // ex. '../../wwwroot/dist'
   filename: '[name].js', // Substitutes [name] with the entry name, results in app.js
   publicPath: '/'
 },

Change your script to:

"scripts": {
    "stand-alone": "webpack --config=webpack.config.js",
},

If you are using Vue + Webpack, I recommend that you take a look to vue-cli and generate a project using the webpack template. It is more advanced, but you can see the documentation and get an idea of what you are missing.

Run the following:

npm install -g vue-cli // install vue cli globally

vue init webpack my-project // create a sample project

If you want to generate multiple output files, you can have more than one entry point like so:

  entry: {
    app: ['./path/to/file.js', './path/to/file2.js'],
    mixins: './path/to/mixins.js',
    vendors: ['./path/to/vendor.js', './path/to/vendor2.js']
  },

This will write to disk ./path/to/assets/app.js, ./path/to/assets/mixins.js, /path/to/assets/vendors.js.

Upvotes: 10

Related Questions