jcubic
jcubic

Reputation: 66470

How to create output filename with given name in webpack?

I have library that use ES modules and I want to generate UMD file in ES5. I have config like this:

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

module.exports = {
    entry: {
        index: path.resolve('./src/index.js')
    },
    output: {
        library: 'name',
        libraryTarget: 'umd',
        path: path.resolve(__dirname, 'dist'),
        filename: 'umd.min.js'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['env']
                }
            }
        ]
    },
    stats: {
        colors: true
    },
    mode: 'production',
    devtool: 'source-map'
};

and webpack create file main.js how can I make output file umd.min.js?

> webpack --mode production

Hash: 98ccf0949bfdf066246a
Version: webpack 4.44.0
Time: 97ms
Built at: 25.07.2020 16:30:31
  Asset      Size  Chunks             Chunk Names
main.js  2.23 KiB       0  [emitted]  main
Entrypoint main = main.js
[0] ./src/index.js + 3 modules 3.6 KiB {0} [built]
    | ./src/index.js 294 bytes [built]
    | ./src/Canvas.js 1.88 KiB [built]
    | ./src/Item.js 1.2 KiB [built]
    | ./src/constants.js 239 bytes [built]

My package.json look like this:

  "type": "module",
  "main": "./src/index.js",
  "unpkg": "./dist/umd.min.js",

So this a bug? Why the file name is main.js?

Upvotes: 3

Views: 18845

Answers (2)

shubham agrawal
shubham agrawal

Reputation: 57

So, by default the webpack emits the chunk name as "main.js", so if you want to rename the chunk name, use the "chunkFilename" option in the output object of your webpack config file, here is the example how i did that:

output: {
filename: env === 'development' ? '[name].js' : '[name].[hash].js',
path: path.resolve(__dirname, '../dist'),
chunkFilename: 'scripts/[name].[hash].js',},

in your case you should do:

chunkFilename: 'umd.min.js'

Upvotes: 5

jcubic
jcubic

Reputation: 66470

The problem is that webpack-cli suggest to rename the file to cjs but don't say that it's not loaded by default, you need to explicitly add --config with the filename when running webpack.

See this issue:

https://github.com/webpack/webpack-cli/issues/1165

Upvotes: 0

Related Questions