From my initial understanding of webpack's multiple entry point such as
entry: {
a: "./a",
b: "./b",
c: ["./c", "./d"]
},
output: {
path: path.join(__dirname, "dist"),
filename: "[name].entry.js"
}
It will bundle them as a.entry.js, b.entry.js and c.entry.js. There is no d.entry.js since it's part of c.
However at work, these values are confusing me so much. Why is the value an http link and not a file?
app: [
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:21200',
'./lib/index.js'
],
test: [
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:21200',
'./test/test.js'
]
As already stated in a comment on the question, the HTTP URLs are used for webpack-dev-server and its hotloading module. However, you want to ommit those modules for the production version of your bundle, since you don't need the hotloading and it makes your bundle easily over 10.000 lines of code (additionally!).
For the personal interest of the poster, here is an example production config (minimalistic), for a project of mine (called dragJs).
// file: webpack.production.babel.js
import webpack from 'webpack';
import path from 'path';
const ROOT_PATH = path.resolve('./');
export default {
entry: [
path.resolve(ROOT_PATH, "src/drag")
],
resolve: {
extensions: ["", ".js", ".scss"]
},
output: {
path: path.resolve(ROOT_PATH, "build"),
filename: "drag.min.js"
},
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: path.resolve(ROOT_PATH, 'src')
},
{
test: /\.scss$/,
loader: 'style!css!sass'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
A few things:
I only use one entry point, but you could use multiple, just as you do in your example
The entry point only refers to my js file - no webpack-dev-server for production
The config file is written using ECMAScript2015 (thus the name *.babel.js)
It uses sourcemaps and an uglify optimization plugin
The presets for the babel-loader are specified in my .babelrc file
Run webpack with this config via webpack -p --config ./webpack.production.babel.js
If there are any further questions, I would be grateful to answer them in the comments.
Related
I'm trying to build a progressive web app, with support for offline usage.
According to MDN, the way to make PWAs work offline is to add the required resources to a cache in the service worker. This requires that the service worker code knows each of the output files. Ideally, this shouldn't be harcoded, and should be generated by webpack, since it knows what files it generates.
I'm struggling to actually generate this list. From my search, there are two plugins that can generate a json file containing a list of the files - webpack-assets-manifest and webpack-manifest-plugin. I can use these in combination with separate targets to generate a manifest with the page files. But I can't import the manifest, since webpack doesn't actually write the manifest until everything is done.
How can I import a list of files that one entry point generates and use them in another entry point/module?
webpack.config.js:
const path = require('path');
const WebpackAssetsManifest = require('webpack-assets-manifest');
const frontend = {
mode: "development",
entry: {
page:"./src/page/page.tsx",
},
devtool: 'inline-source-map',
output: {
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.html?$|\.png$/,
type: "asset/resource",
generator: {
filename: "[name][ext]",
},
},
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
},
{
test: /\.json$/,
type: "asset/resource",
exclude: /node_modules/,
}
],
},
resolve: {
extensions: [".html", ".tsx", ".ts", ".js"],
},
plugins: [
new WebpackAssetsManifest({
output: "page-files.json",
writeToDisk: true,
}),
]
};
const serviceworker = {
mode: "development",
entry: {
serviceworker: "./src/serviceworker/serviceworker.ts",
},
devtool: 'inline-source-map',
output: {
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.html?$|\.png$/,
type: "asset/resource",
generator: {
filename: "[name][ext]",
},
},
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
},
{
test: /\.json$/,
resourceQuery: /link/,
type: "asset/resource",
exclude: /node_modules/,
},
{
test: /\.json$/,
resourceQuery: /str/,
type: "asset/source",
exclude: /node_modules/,
}
],
},
resolve: {
extensions: [".html", ".tsx", ".ts", ".js"],
},
};
module.exports = [frontend, serviceworker];
serviceworker.ts:
import files from "../../dist/page-files.json?str";
console.log(files);
Error is:
Module not found: Error: Can't resolve '../../dist/page-files.json?str' in '<REDACTED>/src/serviceworker'
(When I build it again, it will find the file from the previous build)
Rather than relying on pre-existing webpack plugins to generate assets, I think you're going to need to write your own plugin for this use case. And if you want that plugin to write the manifest to an entry that itself needs to be bundled/compiled, creating a child compilation in that plugin would be the way to do it.
This is unfortunately not a straightforward task, but you can refer to the source code for the workbox-webpack-plugin's InjectManifest plugin, which more or does what you describe, as inspiration.
Alternatively... you can just use InjectManifest directly, if that meets your use case. While it's part of the Workbox family of libraries, InjectManifest will only actually do two things: process the entry file you pass in as swSrc via a child compilation, and replace the symbol self.__WB_MANIFEST anywhere in that swSrc file with an array of {url: '...', revision: '...'} entries generated based on the assets in the main configuration, filtered by any include/exclude parameters.
So if you don't plan on using Workbox, you can just make use of that self.__WB_MANIFEST value from your own code.
// service-worker.ts
const manifest = self.__WB_MANIFEST || [];
self.addEventListener('install', (event) => {
// Your code to cache the contents of manifest goes here.
});
// webpack.config.js
const {InjectManifest} = require('workbox-webpack-plugin');
module.exports = {
// ...other webpack config...
plugins: [
new InjectManifest({
swSrc: 'src/service-worker.ts',
swDest: 'service-worker.js',
// ...exclude/include config here...
}),
],
};
The reason behind this behavior is that webpack runs these 2 configurations parallelly. By forcing webpack to run sequentially we can fix the problem.
To do serial processing, add module.exports.parallelism = 1; at end of your webpack config.
module.exports = [frontend, serviceworker];
module.exports.parallelism = 1;
Here is the documentation from webpack, https://webpack.js.org/configuration/configuration-types/#parallelism
I am going through webpack tutorials and it teaches how it is possible to minify and output images that have been imported in main index.js file.
However I would like to minify all image assets, regardless whether they were imported in the index.js or not. Something that was easily done in gulp by having a watch set up on the folder. Does webpack follow same format?
This is my webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules : [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
},
{
loader: 'image-webpack-loader',
}
]
}
]
}
};
No, webpack does not follow the same "logic" as gulp. Webpack """""watches""""" for changes in files that are linked throughout the entire dependency tree. This means that the file you wan't to touch HAS TO BE imported somewhere.
When I configure Webpack for this code base, Webpack complains that it Can't resolve 'babel-loader'. What exactly is failing, and how can I ask Webpack what its complaint is?
The Webpack configuration:
// webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './source/main.jsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js',
},
resolve: {
modules: [
path.resolve(__dirname, 'source'),
'/usr/share/javascript',
'/usr/lib/nodejs',
],
},
module: {
loaders: [
// Transform JSX with React.
{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react'],
},
},
],
},
};
The entry module:
// source/main.jsx
"use strict";
import Application from './components/Application';
const applicationElement = <Application />;
ReactDOM.render(
applicationElement,
document.getElementById('application'),
);
Is the problem something like a search path, and if so why can't the error tell me what setting I need to correct?
The babel-loader module is definitely installed. (I therefore don't want to install it again – so npm install won't help – I am trying to tell Webpack to use it from the already-installed location.) Its package definition is at /usr/lib/nodejs/babel-loader/package.json.
I've pointed Webpack's resolver there – instead of its default resolver behaviour – using the resolve.modules list of search paths. Correct?
So the resolver should be able to find it there by the specified search path /usr/lib/nodejs and the name babel-loader, no?
(This raises a separate question, about how to convince Webpack to just tell me what it's looking for so it can be diagnosed more easily.)
How can I tell Webpack the specific location it should use to resolve that babel-loader name?
The Webpack configuration setting resolve is for modules that are imported. The loaders are resolved differently; the resolveLoader setting configures how to resolve the loaders specifically.
So, adding resolveLoader to the Webpack configuration works:
// webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './source/main.jsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js',
},
resolve: {
// Configure how Webpack finds modules imported with `import`.
modules: [
path.resolve(__dirname, 'source'),
'/usr/share/javascript',
'/usr/lib/nodejs',
],
},
resolveLoader: {
// Configure how Webpack finds `loader` modules.
modules: [
'/usr/lib/nodejs',
],
},
module: {
loaders: [
// Transform JSX with React.
{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react'],
},
},
],
},
};
I think that the webpack.config you're looking for is the following:
module: {
loaders: [
{test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
]
}
Hope helps :)
I have an issue with webpack build times in my react application. Everything builds fine but it takes a long time.
Even I change just the JavaScript files the CSS rebuilds?
Also the CSS compilation is taking a longer than I think it should be (correct me if I am wrong)?
I am running a Core i7 with 16gb of Ram and the build is taking about a minute which is becoming very annoying during development when it's a one line change and you have to wait near enough a minute before you can see your changes in the browser?
Is this the wrong approach?
const CleanObsoleteChunks = require('webpack-clean-obsolete-chunks');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const DashboardPlugin = require('webpack-dashboard/plugin');
const path = require('path');
const webpack = require('webpack');
const BUILD_DIR = path.resolve(__dirname, '../dist');
const APP_DIR = path.resolve(__dirname, 'src/');
const config = {
devtool: 'source-map',
entry: {
"ehcp-coordinator": [
APP_DIR + '/index.js'
]
},
output: {
path: `${BUILD_DIR}/js/`,
filename: '[name].js',
chunkFilename: '[name]-chunk.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', 'es2017', 'react', 'stage-0'],
plugins: ['transform-runtime', 'transform-decorators-legacy', 'transform-class-properties', 'syntax-dynamic-import',
["import", {"libraryName": "antd", "style": false}]]
}
}
}, {
test: /\.less$/,
use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "less-loader"
}]
})
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': "'development'"
}),
new webpack.optimize.UglifyJsPlugin({
'sourceMap': 'source-map'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: '[name].js',
minChunks(module, count) {
var context = module.context;
return context && context.indexOf('node_modules') >= 0;
}
}),
new ExtractTextPlugin("../css/[name].css")
],
resolve: {
modules: [
path.resolve('./'),
path.resolve('./node_modules'),
],
extensions: ['.js', '.json']
}
};
module.exports = config;
As discussed in the comments, here are the most obvious changes you could make to speed up your build:
UglifyJsPlugin and ExtractTextPlugin are very heavy in terms of their impact on your compilation time, while not actually presenting many tangible benefits in development. Check process.env.NODE_ENV in your config script, and enable/disable them depending on whether you're doing a production build or not.
In place of ExtractTextPlugin, you can use style-loader in development to inject CSS into the head of the HTML page. This can cause a brief flash of unstyled content (FOUC) when the page loads, but is much quicker to build.
If you're not already, use webpack-dev-server rather than just running Webpack in watch mode - using the dev server compiles the files in memory instead of saving them to disk, which further decreases the compile times in development.
This does mean you'll have to manually run a build when you want to have the files written to disk, but you'll need to do that to switch to your production config anyway.
Not sure if this has any impact on performance, but the resolve section of your config doesn't meaningfully differ from the defaults, and you should be able to remove it without causing any issues.
In my case I updated devtool property to false.
Article on Medium: https://medium.com/#gagan_goku/hot-reloading-a-react-app-with-ssr-eb216b5464f1
Had to solve the same problem for my React app (HELO) with SSR. Things get complicated with SSR, but thankfully webpack gets a lot faster if you specify --mode=development, because it does it in memory.
webpack-dev-server did not work for me because I need the client.js bundle for the SSR client to work properly. Here's my setup:
webpack.config.js:
const path = require('path');
module.exports = {
entry: {
client: './src/client.js', // client side companion for SSR
// bundle: './src/bundle.js', // Pure client side app
},
output: {
path: path.resolve(__dirname, 'assets'),
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
loader: "babel-loader",
options: {
presets: [
'#babel/preset-env',
{'plugins': ['#babel/plugin-proposal-class-properties']},
],
}
}
]
},
watchOptions: {
aggregateTimeout: 1000,
poll: 500,
ignored: /node_modules/,
}
};
package.json:
"scripts": {
// IMP: --mode=development
"run-dev-ssr": "webpack --config webpack.config.js --watch --mode=development & babel src -d dist --watch & browser-refresh dist/server.js"
}
.browser-refresh-ignore:
node_modules/
static/
.cache/
.*
*.marko.js
*.dust.js
*.coffee.js
.git/
# Add these files to ignore, since webpack is storing the compiled output to assets/ folder
src/
dist/
Build times without mode:
Hash: 81eff31301e7cb74bffd
Version: webpack 4.29.5
Time: 4017ms
Built at: 05/10/2019 9:44:10 AM
Hash: 64e10f26caf6fe15068e
Version: webpack 4.29.5
Time: 2548ms
Time: 5680ms
Time: 11343ms
Build times with mode:
Hash: 27eb1aabe54a8b995d67
Version: webpack 4.29.5
Time: 4410ms
Time: 262ms
Time: 234ms
Time: 162ms
I'm working on a new module for an existing project that still uses requireJS for module loading. I'm trying to use new technologies for my new module like webpack (which allows me to use es6 loaders using es6 imports). It seems like webpack can't reconcile with requireJS syntax. It will say things like: "Module not found: Error: Can't resolve in ".
Problem: Webpack won't bundle files with requireJS/AMD syntax in them.
Question: Is there any way to make webpack play nice with requireJS?
My final output must be in AMD format in order for the project to properly load it. Thanks.
I had the same question and I managed to achieve it. Below is the same webpack.config.js file.
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
let basePath = path.join(__dirname, '/');
let config = {
// Entry, file to be bundled
entry: {
'main': basePath + '/src/main.js',
},
devtool: 'source-map',
output: {
// Output directory
path: basePath + '/dist/',
library: '[name]',
// [hash:6] with add a SHA based on file changes if the env is build
filename: env === EnvEnum.BUILD ? '[name]-[hash:6].min.js' : '[name].min.js',
libraryTarget: 'amd',
umdNamedDefine: true
},
module: {
rules: [{
test: /(\.js)$/,
exclude: /(node_modules|bower_components)/,
use: {
// babel-loader to convert ES6 code to ES5 + amdCleaning requirejs code into simple JS code, taking care of modules to load as desired
loader: 'babel-loader',
options: {
presets: ['es2015'],
plugins: []
}
}
}, { test: /jQuery/, loader: 'expose-loader?$' },
{ test: /application/, loader: 'expose-loader?application' },
{ test: /base64/, loader: 'exports-loader?Base64' }
]
},
resolve: {
alias: {
'jQuery': 'bower_components/jquery/dist/jquery.min',
'application': 'main',
'base64': 'vendor/base64'
},
modules: [
// Files path which will be referenced while bundling
'src/**/*.js',
'src/bower_components',
path.resolve('./src')
],
extensions: ['.js'] // File types
},
plugins: [
]
};
module.exports = config;