How to Ignore a Folder when using watch with Webpack - javascript

I have the following function:
export default function(path, urlKey = 'static') {
if (urlKey === 'static') {
path = require(`~/static${path}`).default;
}
urlKey = Object.keys(config.app.urls).includes(urlKey) ? urlKey : 'static';
return (config.app.urls[urlKey] + '/' + path).replace(/([^:]\/)\/+/g, "$1");
};
As you can see, I am using a dynamic require which I believe utilises require.context. When my webpack bundles, it builds all the files in the static folder. The ~/static part of the path is an alias to my static folder in the root directory.
When using the watch mode of webpack, the bundling goes into an endless loop.
I have tried various things such as watchOptions.ignored and the WatchIgnorePlugin but neither of these have worked.
These are my two attempts with the above solutions:
watchOptions: {
ignored: /static/
}
and
plugins:[
new WatchIgnorePlugin([
path.resolve(__dirname, '..', 'static')
]),
]
Can anyone suggest what I am missing here?

I have also been experiencing the issue of endless rebuilds. After many tries, I was finally able to exclude the static folder by using the WatchIgnorePlugin in my webpack.dev.config.js:
devWebpackConfig = merge(baseWebpackConfig, {
...
plugins: [
...
new webpack.WatchIgnorePlugin([
path.resolve(__dirname, '../static')
])

Related

configure webpack only for production using vue-cli3

I try to compile my vue project a bit differently in local and in production.
As you will see, There is a massive difference in my vue.config.js file...joke
// this is the file when I'm in dev version
module.exports = {
lintOnSave: false,
}
// this is the file when I'm in prod version
module.exports = {
lintOnSave: false,
configureWebpack: {
output: {
publicPath: '/static/'
}
}
}
I was checking for the new mode in webpack 4, or in the vue cli documentation, I didn't find anything which avoid to change the vue.config.js MANUALLY whenever I want to build local or prod. This is not CI ready, and I feel sh*t doing it, so If you guys have any tips to do it properly.
Thanks.
well, I'm not sure that The things to do, but you can use the variable 'process.env.NODE_ENV' in the vue.config.js file (which I didn't expect). so
if (process.env.NODE_ENV === 'production') {
module.exports = {
configureWebpack: {
output: {
publicPath: '/static/'
}
}
}
}
else{
module.exports = {
lintOnSave: true
}
}
looks to work properly

How to inject Webpack build hash to application code

I'm using Webpack's [hash] for cache busting locale files. But I also need to hard-code the locale file path to load it from browser. Since the file path is altered with [hash], I need to inject this value to get right path.
I don't know how can get Webpack [hash] value programmatically in config so I can inject it using WebpackDefinePlugin.
module.exports = (env) => {
return {
entry: 'app/main.js',
output: {
filename: '[name].[hash].js'
}
...
plugins: [
new webpack.DefinePlugin({
HASH: ***???***
})
]
}
}
In case you want to dump the hash to a file and load it in your server's code, you can define the following plugin in your webpack.config.js:
const fs = require('fs');
class MetaInfoPlugin {
constructor(options) {
this.options = { filename: 'meta.json', ...options };
}
apply(compiler) {
compiler.hooks.done.tap(this.constructor.name, stats => {
const metaInfo = {
// add any other information if necessary
hash: stats.hash
};
const json = JSON.stringify(metaInfo);
return new Promise((resolve, reject) => {
fs.writeFile(this.options.filename, json, 'utf8', error => {
if (error) {
reject(error);
return;
}
resolve();
});
});
});
}
}
module.exports = {
// ... your webpack config ...
plugins: [
// ... other plugins ...
new MetaInfoPlugin({ filename: 'dist/meta.json' }),
]
};
Example content of the output meta.json file:
{"hash":"64347f3b32969e10d80c"}
I've just created a dumpmeta-webpack-plugin package for this plugin. So you might use it instead:
const { DumpMetaPlugin } = require('dumpmeta-webpack-plugin');
module.exports = {
...
plugins: [
...
new DumpMetaPlugin({
filename: 'dist/meta.json',
prepare: stats => ({
// add any other information you need to dump
hash: stats.hash,
})
}),
]
}
Please refer to the Webpack documentation for all available properties of the Stats object.
Seems like it should be a basic feature but apparently it's not that simple to do.
You can accomplish what you want by using wrapper-webpack-plugin.
plugins: [
new WrapperPlugin({
header: '(function (BUILD_HASH) {',
footer: function (fileName) {
const rx = /^.+?\.([a-z0-9]+)\.js$/;
const hash = fileName.match(rx)[1];
return `})('${hash}');`;
},
})
]
A bit hacky but it works — if u don't mind the entire chunk being wrapped in an anonymous function.
Alternatively you can just add var BUILD_HASH = ... in the header option, though it could cause problem if it becomes a global.
I created this plugin a while back, I'll try to update it so it provides the chunk hash naturally.
On server, you can get the hash by reading the filenames (example: web.bundle.f4771c44ee57573fabde.js) from your bundle folder.
You can pass the version to your build using webpack.DefinePlugin
If you have a package.json with a version, you can extract it like this:
const version = require("./package.json").version;
For example (we stringified the version):
new webpack.DefinePlugin({
'process.env.VERSION': JSON.stringify(version)
}),
then in your javascript, the version will be available as:
process.env.VERSION
The WebpackManifestPlugin is officially recommended in the output management guide. It writes a JSON to the output directory mapping the input filenames to the output filenames. Then you can inject those mapped values into your server template.
It's similar to Dmitry's answer, except Dmitry's doesn't appear to support multiple chunks.
That can be done with Webpack Stats Plugin. It gives you nice and neat output file with all the data you want. And it's easy to incorporate it to the webpack config files where needed.
E.g. To get hash generated by Webpack and use it elsewhere.
Could be achieved like:
# installation
npm install --save-dev webpack-stats-plugin
yarn add --dev webpack-stats-plugin
# generating stats file
const { StatsWriterPlugin } = require("webpack-stats-plugin")
module.exports = {
plugins: [
// Everything else **first**.
// Write out stats file to build directory.
new StatsWriterPlugin({
stats: {
all: false,
hash: true,
},
filename: "stats.json" // Default and goes straight to your output folder
})
]
}
# usage
const stats = require("YOUR_PATH_TO/stats.json");
console.log("Webpack's hash is - ", stats.hash);
More usage examples in their repo
Hope that helps!

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.

How to use gulp webpack-stream to generate a proper named file?

Currently we're using Webpack for our Module loader, and Gulp for everything else (sass -> css, and the dev/production build process)
I want to wrap the webpack stuff into gulp, so all I have to do is type gulp and it starts, watches and runs webpack and the rest of what our gulp is setup to do.
So I found webpack-stream and implemented it.
gulp.task('webpack', function() {
return gulp.src('entry.js')
.pipe(webpack({
watch: true,
module: {
loaders: [
{ test: /\.css$/, loader: 'style!css' },
],
},
}))
.pipe(gulp.dest('dist/bundle.js'));
});
The problem is that it generates a random character name for the .js file, how are we suppose to use that in our app?
From the github repo:
The above will compile src/entry.js into assets with webpack into dist/ with the output filename of [hash].js (webpack generated hash of the build).
How do you rename these files? Also the new gulp task generates a new file everytime I save an edit:
I can't use c2212af8f732662acc64.js I need it to be named bundle.js or something else normal.
Our Webpack config:
var webpack = require('webpack');
var PROD = JSON.parse(process.env.PROD_DEV || '0');
// http://stackoverflow.com/questions/25956937/how-to-build-minified-and-uncompressed-bundle-with-webpack
module.exports = {
entry: "./entry.js",
devtool: "source-map",
output: {
devtoolLineToLine: true,
sourceMapFilename: "app/assets/js/bundle.js.map",
pathinfo: true,
path: __dirname,
filename: PROD ? "app/assets/js/bundle.min.js" : "app/assets/js/bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
},
plugins: PROD ? [
new webpack.optimize.UglifyJsPlugin({minimize: true})
] : []
};
There was a comment to Leon Gaban's answer as to what his webpack.config.js looked like. Rather than answer that within a comment, I'm providing it here so it formats better.
Per the docs for webpack-stream, "You can pass webpack options in with the first argument"...
So, I did the following to force webpack to use the same output name each time (for me, I used bundle.js):
gulp.task('webpack', ['babelify'],
() => {
return gulp.src('Scripts/index-app.js')
.pipe(webpack({output: {filename: 'bundle.js'} }))
.pipe(debug({ title: 'webpack:' }))
.pipe(gulp.dest('Scripts/'));
});
The key being the options inside webpack(), which are:
{output: {filename: 'bundle.js'} }
As recommended in docs you should use the vinyl-named package on the pipe before webpack-stream. This way you can use a more cleaner Webpack configuration. The following is the task definition i use myself:
'use strict';
const gulp = require('gulp'),
named = require('vinyl-named'),
webpack = require('webpack-stream');
gulp.task('webpack', function () {
gulp.src(['./src/vendor.js', './src/bootstrap.js', './src/**/*.spec.js'])
.pipe(named())
.pipe(webpack({
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['es2015', 'angular2']
}
}
]
}
}))
.pipe(gulp.dest('./build'))
});
The only problem i'm facing with this task definition is that the subfolder are loosed. For example ./src/components/application.spec.js will produce ./build/application.spec.js instead of ./build/components/application.spec.js.
Ah I read on a bit further and figured it out:
gulp.task('webpack', function() {
return gulp.src('entry.js')
.pipe(webpack( require('./webpack.config.js') ))
.pipe(gulp.dest('app/assets/js'));
});
^ here I can just pass in my actual webpack.config and it will use the paths I have already set in there. In my case I just removed app/assets/js since I have that path in now gulp instead.
Still no earthly idea though, why with the first task I created, it generates random hash filenames?
Rather than giving your javascript a fixed filename, a better solution would be to use gulp-inject and insert the generated hash filename into a script tag. This means you don't have to worry about cache expiry on the compiled javascript (which is why the hash filename is being used in the first place).
const inject = require('gulp-inject');
gulp.task('webpack', function() {
const index = './src/index.html';
const scripts = gulp.src('entry.js')
.pipe(webpack( require('./webpack.config.js') ))
.pipe(gulp.dest('dist/js'));
return target
.pipe(inject(scripts))
.pipe(gulp.dest('dist/'));
});
and of course you need the inject section in your src/index.html:
<!DOCTYPE html>
<html>
<head>
<title>index page</title>
</head>
<body>
<!-- inject:js -->
<!-- endinject -->
</body>
</html>

In webpack, how can I have different output directories for multiple entry points?

I have the following webpack configuration with multiple entry points...
module.exports = {
entry: {
somePage: "./scripts/someDir/somePage.js",
anotherPage: "./scripts/someDir/someSubDir/anotherPage.js"
},
output: {
path: path.resolve(__dirname, 'out'),
filename: '[name].js'
},
...
Is it possible to set a different output path for each entry?
Instead of getting an output of...
/out/somePage.js
/out/anotherPage.js
I want...
/out/someDir/somePage.js
/out/someDir/someSubDir/anotherPage.js
The ideal solution for me would be for output.path to accept a function. For example...
...
output: {
path: function (name, hash) {
return path.resolve(__dirname, myMapOfFilenamesToDirs[name]);
},
filename: '[name].js'
},
Does anyone know if this is possible or if there is an existing plugin that can accomplish this?
EDIT I don't want to use multiple config entries (multi-compiler) because I won't be able to create a shared file among the entry points with CommonsChunkPlugin anymore
A bit hacky, but this should do the trick.
module.exports = {
entry: {
"somePage": "./scripts/someDir/somePage.js",
"someSubDir/anotherPage": "./scripts/someDir/someSubDir/anotherPage.js"
},
output: {
path: path.resolve(__dirname, 'out/someDir'),
filename: '[name].js'
},
// Etc.
}
You cannot set the path to a function, webpack won't call it for you.
You can return an array of configurations for webpack to execute. I think that will give you enough control over the output path to achieve what you need.
I had the same issue today, adding on to the answer from #quentin-roy, https://stackoverflow.com/a/33086806/6552940
You can also create the output path mappings for input files using glob and the following callback. Adjust your glob pattern according to your needs. The following pattern and callback if applied on the directory structure
- src
- file01.ts
lib
- file02.ts
will result in
- dist
- file01.js
lib
- file02.js
config = {
entry: () => {
const entries = {};
glob.sync("./src/**/*.ts").forEach(filePath => {
entries[
path
.relative("./src", filePath)
.replace(path.extname(filePath), "")
] = filePath;
});
console.debug(
`Entries created:\n${JSON.stringify(entries, undefined, 4)}`,
);
return entries;
},
output: {
filename: "[name].js",
path: path.resolve(__dirname, "dist"),
},
}
After some evaluations I'm using the Webpack-watched-glob-entries-plugin for some time, because it is small, does what we need and works also in watch mode.
If you need even more ideas take a look here Wildcards in entry points.

Categories

Resources