Output filename for gulp/webpack task - javascript

I'm using webpack-stream to integrate webpack into a gulp task, as below:
var gulp = require("gulp");
// var webpack = require('gulp-webpack');
var webpack = require('webpack-stream');
gulp.task("min:webpack",
function () {
return gulp.src('./App/App.js')
.pipe(webpack({
// watch: true,
module: {
entry: './App/App.js',
output: {
filename: 'App.bundle.js'
},
devtool: 'source-map'
}
}))
.pipe(gulp.dest('./App'));
});
Everything seems to be working as expected, except that the output file is always something like 6f7af85206d7f2f6536d.js instead of the expected App.bundle.js. In other similar questions (e.g., How to use gulp webpack-stream to generate a proper named file?), I've read that it was fixed effectively by specifying output: { filename: 'something'} in the configuration, but you can see that I'm doing that.
Any suggestions? Anything I'm overlooking?

OK, dumb mistake on my part. I had the configuration specified incorrectly. This config works as expected:
gulp.task("min:webpack",
function () {
return gulp.src('./App/App.js')
.pipe(webpack({
// watch: true,
entry: './App/App.js',
output: {
filename: 'App.bundle.js'
},
devtool: 'source-map'
}))
.pipe(gulp.dest('./App'));
});

Related

webpack/terser: How can I exclude a package from minification, but still include that package in the packed result?

I've found a number of solutions for excluding particular modules from minification, but all of the solutions I've seen so far not only skip minification of those packages, they cause those packages to be completely omitted from webpack's output, requiring you to provide the omitted code by some other means.
What I want to do is continue to package all needed code into one single output file, but simply have sections of that output non-minified. Is that possible?
The reason that I want to do this in this particular case is that the mysql package is failing after minification. For the moment I've disabled all minification, but I'd rather not solve this problem that way.
const webpack = require('webpack');
const LicensePlugin = require('webpack-license-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
const mode = process.env.NODE_ENV || 'production';
// noinspection JSUnresolvedFunction
module.exports = {
mode,
entry: './app/app.ts',
target: 'node',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js'
},
node: {
__dirname: false,
__filename: false,
global: true
},
resolve: {
extensions: ['.ts', '.js'],
mainFields: ['fesm2015', 'module', 'main']
},
module: {
rules: [
{
test: /\.ts$/,
use: [
'ts-loader',
]
}
]
},
optimization: {
// TODO: Minification breaks mysql. How to exclude mysql from minification, but include in output?
minimize: false, // mode === 'production',
minimizer: [new TerserPlugin({
exclude: /node_modules\/mysql/, // <-- This doesn't work
terserOptions: {
output: { max_line_len: 511 },
}
})],
},
devtool: 'source-map',
ignoreWarnings: [{ message: /require function is used in a way|the request of a dependency is an expression/ }],
plugins: [
new webpack.BannerPlugin({ banner: '#!/usr/bin/env node', raw: true }),
new LicensePlugin({
outputFilename: '3rdpartylicenses.txt',
excludedPackageTest: name => /^(asynclist|emitter)/.test(name)
})
]
};
Update: The particular issue with mysql and minification seems to be mangling of variable and/or function names. If I set the mangle option to false, I can minify all of the code, including mysql, successfully. I have yet to figure out which specific names can't be mangled without causing problems.

Uglify JS Webpack plugin for Webpack Stream (Gulp + Webpack)

I am trying to use Gulp + Webpack workflow
Most Things are working at https://github.com/IamManchanda/gulp-webpack/
But when I am trying to Implement UglifyjsWebpackPlugin as per the mentioned docs, it just doesn't seem to work. I don't get any errors, what I get is simply the non-uglified code!
Here is my code for same => https://github.com/IamManchanda/gulp-webpack/pull/7/
In fact to be more specific, here is my config.production.js
const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map',
output: {
filename: 'scripts.js',
},
optimization: {
minimizer: [
new UglifyjsWebpackPlugin({
sourceMap: true,
}),
],
},
};
Am I missing something? Do I need some more RTFM? Can you guys help me here
Let me know if you need any other details. Thanks in Advance.
Edit: Here is the video demo of the same issue: https://drive.google.com/file/d/1Xa1E3vnXR2_fFuqZ8b5Hu4-kMb2gD2FT/view
Please change output filename to scripts.min.js, and use property compress as true.
const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map',
output: {
filename: 'scripts.min.js',
},
optimization: {
minimizer: [
new UglifyjsWebpackPlugin({
sourceMap: true,
minify(file, sourceMap) {
// https://github.com/mishoo/UglifyJS2#minify-options
const uglifyJsOptions = { /* your `uglify-js` package options */ };
if (sourceMap) {
uglifyJsOptions.sourceMap = {
content: sourceMap,
};
}
return require('uglify-js').minify(file, uglifyJsOptions);
}
}),
],
},
};
So as I needed this on urgent basis, I have used gulp to do the job instead of webpack ... That being said ... still looking for webpack solution
Anyways here is my Gulp based (gulpfile.js) Solution => https://github.com/IamManchanda/gulp-webpack/pull/8
1.
yarn add --dev gulp-uglify
2.
const gulpUglify = require('gulp-uglify');
3.
...((mode === 'production') ? [gulpUglify()] : []),
I think what matters for me right now is that this works for me :)
Just define
new UglifyjsWebpackPlugin in plugins
{
'plugins': [
new UglifyJsPlugin({
'sourceMap': false,
'parallel': true
})
]
}
Don't use optimization.minimizer

Webpack DllPlugin with gulp: Cannot find module '... vendor-manifest.json'

I have a rather large React application built with webpack 2. The application is embedded into a Drupal site as a SPA within the existing site. The Drupal site has a complex gulp build setup and I can't replicate it with webpack, so I decided to keep it.
I have split my React application into multiple parts using the DllPlugin / DllReferencePlugin combo which is shipped out of the box in webpack 2. This works great, and I get a nice vendor-bundle when building with webpack.
The problem is when I try to run my webpack configuration in gulp, I get an error. I might be doing it wrong, as I have not been able to find much documentation on this approach, but nevertheless, it's not working for me.
It looks like it's trying to include the the manifest file from my vendor-bundle before creating it.
Whenever I run one of my defined gulp tasks, like gulp react-vendor I get an error, saying that it cannot resolve the vendor-manifest.json file.
If I on other hand run webpack --config=webpack.dll.js in my terminal, webpack compiles just fine and with no errors.
I have included what I think is the relevant files. Any help on this is appreciated.
webpack.config.js
// Use node.js built-in path module to avoid path issues across platforms.
const path = require('path');
const webpack = require('webpack');
// Set environment variable.
const production = process.env.NODE_ENV === "production";
const appSource = path.join(__dirname, 'react/src/');
const buildPath = path.join(__dirname, 'react/build/');
const ReactConfig = {
entry: [
'./react/src/index.jsx'
],
output: {
path: buildPath,
publicPath: buildPath,
filename: 'app.js'
},
module: {
rules: [
{
exclude: /(node_modules)/,
use: {
loader: "babel-loader?cacheDirectory=true",
options: {
presets: ["react", "es2015", "stage-0"]
},
},
},
],
},
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
'./react/src/'
],
extensions: ['.js', '.jsx', '.es6'],
},
context: __dirname,
devServer: {
historyApiFallback: true,
contentBase: appSource
},
// TODO: Split plugins based on prod and dev builds.
plugins: [
new webpack.DllReferencePlugin({
context: path.join(__dirname, "react", "src"),
manifest: require(path.join(__dirname, "react", "vendors", "vendor-manifest.json"))
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
filename: 'webpack-loader.js'
}),
]
};
// Add environment specific configuration.
if (production) {
ReactConfig.plugins.push(
new webpack.optimize.UglifyJsPlugin()
);
}
module.exports = [ReactConfig];
webpack.dll.js
const path = require("path");
const webpack = require("webpack");
const production = process.env.NODE_ENV === "production";
const DllConfig = {
entry: {
vendor: [path.join(__dirname, "react", "vendors", "vendors.js")]
},
output: {
path: path.join(__dirname, "react", "vendors"),
filename: "dll.[name].js",
library: "[name]"
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, "react", "vendors", "[name]-manifest.json"),
name: "[name]",
context: path.resolve(__dirname, "react", "src")
}),
// Resolve warning message related to the 'fetch' node_module.
new webpack.IgnorePlugin(/\/iconv-loader$/),
],
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
extensions: ['.js', '.jsx', '.es6'],
},
// Added to resolve a dependency issue in this build #https://github.com/hapijs/joi/issues/665
node: {
net: 'empty',
tls: 'empty',
dns: 'empty'
}
};
if (production) {
DllConfig.plugins.push(
new webpack.optimize.UglifyJsPlugin()
);
}
module.exports = [DllConfig];
vendors.js (to determine what to add to the Dll)
require("react");
require("react-bootstrap");
require("react-dom");
require("react-redux");
require("react-router-dom");
require("redux");
require("redux-form");
require("redux-promise");
require("redux-thunk");
require("classnames");
require("whatwg-fetch");
require("fetch");
require("prop-types");
require("url");
require("validator");
gulpfile.js
'use strict';
const gulp = require('gulp');
const webpack = require ('webpack');
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
// React webpack source build.
gulp.task('react-src', function (callback) {
webpack(reactConfig, function (err, stats) {
callback();
})
});
// React webpack vendor build.
gulp.task('react-vendor', function (callback) {
webpack(vendorConfig, function (err, stats) {
callback();
})
});
// Full webpack react build.
gulp.task('react-full', ['react-vendor', 'react-src']);
NOTE:
If I build my vendor-bundle with the terminal with webpack --config=webpack.dll.js first and it creates the vendor-manifest.json file, I can then subsequently successfully run my gulp tasks with no issues.
This is not very helpful though, as this still will not allow me to use webpack with gulp, as I intend to clean the build before new builds run.
I ended up using the solution mentioned in the end of my question. I build my DLL file first and then I can successfully run my gulp webpack tasks.
One change that can make it easier to debug the issue, is to use the Gulp utility module (gulp-util) to show any webpack errors that might show up during build of webpack, using gulp.
My final gulp setup ended up looking like this:
gulpfile.js
'use strict';
const gulp = require('gulp');
const gutil = require('gulp-util');
const webpack = require('webpack');
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
// React webpack source build.
gulp.task('react', function (callback) {
webpack(reactConfig, function (err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
else {
gutil.log('[webpack]', stats.toString());
}
callback();
});
});
// React webpack vendor build.
gulp.task('react-vendor', function (callback) {
webpack(vendorConfig, function (err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
else {
gutil.log('[webpack]', stats.toString());
}
callback();
});
});
// React: Rebuilds both source and vendor in the right order.
gulp.task('react-full', ['react-vendor'], function () {
gulp.start('react');
});
I hope this might help someone in a similar situation.
Whenever I run one of my defined gulp tasks, like gulp react-vendor I get an error, saying that it cannot resolve the vendor-manifest.json file.
Your gulpfile.js contains this:
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
And webpack.config.js contains this:
new webpack.DllReferencePlugin({
context: path.join(__dirname, "react", "src"),
manifest: require(path.join(__dirname, "react", "vendors", "vendor-manifest.json"))
}),
The require() calls are currently all executed immediately. Whenever you run Gulp, it will evaluate both Webpack configuration files. As currently configured, Node runs the code in webpack.config.js at startup, and from there it sees the require() used in your creation of the DllReferencePlugin, so it will also try to read manifest.json at that time and turn it into an object...which is before it has been built.
You can solve this in one of two ways:
The DllReferencePlugin's manifest option supports either an object (which is what you are currently providing), or else a string containing the path of the manifest file. In other words, it should work if you remove the require() from around your path.join(...) call.
Alternatively, you can also defer the loading of the Webpack config files. Moving your const reactConfig = require('./webpack.config.js'); from the top of the file directly into the gulp task function should be sufficient, assuming that this function is not invoked until after the manifest has been built.

Compress and Minify multiples javascript files into one, with Webpack?

I'm trying to concatenate, minify multiples javascript files into one, with 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.
Best I show examples.
3 javascript files.
app.js
var fnA = function () {
console.log('fnA')
}
global.js
fnA();
main.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
}),
]
};
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.
I put together something simple but you need babel.
https://github.com/vpanjganj/simple-webpack-sample
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
})
]
};
here your 2 modules:
First module, moduleOne.js:
export default function sayHello() {
console.log('hello')
}
moduleTwo.js file:
export default function sayBye() {
console.log('bye')
}
and your main.js file:
import sayHello from './moduleOne'
import sayBye from './moduleTwo'
const myApp = ()=>{
sayHello();
sayBye()
};
myApp();
The command to build:
$ ./node_modules/.bin/webpack --color --display-error-details --config ./webpack.js"

How to minify gulp-webpack file?

Have a follow situation:
gulp.task('webpack', function(cb) {
gulp.src('webpack-init.js')
.pipe(webpack({
output: {
filename: 'bundle.js',
},
}))
.pipe(gulp.dest('./client/js'));
cb();
});
All ok, but i want to minify output file.
If i use gulp-uglify directly -
.pipe(webpack(...))
.pipe(uglify().on('error', gutil.log))
.pipe(gulp.dest('./client/js'));
have an error: "Unexpected token: punc ())]" and others of that ilk.
I found a solution. We can use normal version of webpack (not just gulp-webpack) to provide plugin include capability:
var gulpWebpack = require('gulp-webpack'),
webpack = require('webpack');
gulp.task('webpack', function() {
gulp.src('webpack-init.js')
.pipe(gulpWebpack({
output: {
filename: 'bundle.js',
},
plugins: [new webpack.optimize.UglifyJsPlugin()],
}, webpack))
.pipe(gulp.dest('./client/js'));
});

Categories

Resources