update:
Seem I have solved my problem creating an "hot directory" in my webpack config like that :
My webpack.config.js :
output: {
path: path.join(__dirname, "public"),
filename: "bundle.js",
publicPath: "/public/",
hotUpdateChunkFilename: 'hot/hot-update.js',
hotUpdateMainFilename: 'hot/hot-update.json'
}
My new tree folders :
├── hot
├── package.json
├── src
└── webpack.config.js
But I still wonder how purely create these chunks in memory ?
Any hint would be great,
Thanks
I'm trying currently to work with express hot middleware. I have set my webpack.config, server.js and package.json to work with. It works fine now but generates a lot of bundles on my root directory instead of on memory, hence saturate my root's directory. I can't figure out what is wrong.
The bundle have name like the following :
main.0d50bece383b2f7c93db.hot-update.js
They are created when there is a change on my server or more generally, configuration files it seems.
Here my webpack.js :
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const autoprefixer = require("autoprefixer");
const nodeExternals = require('webpack-node-externals');
const path=require("path");
module.exports = {
mode:"development",
entry: [
"webpack-hot-middleware/client",
"./src/client/index.js"],
output: {
path: path.join(__dirname, "public"),
filename: "bundle.js",
publicPath: "/"
},
devtool: "cheap-module-source-map",
module: {
rules: [
{
test: [/\.svg$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: "file-loader",
options: {
name: "public/media/[name].[ext]",
publicPath: url => url.replace(/public/, "")
}
},
{
test: /js$/,
exclude: /(node_modules)/,
loaders: "babel-loader",
}
]
},
plugins: [
new ExtractTextPlugin({
filename: "css/[name].css"
}),
new (webpack.optimize.OccurenceOrderPlugin || webpack.optimize.OccurrenceOrderPlugin)(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.BROWSER': true,
}),
],
};
here my server.js :
app.use(
require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: webpackConfig.output.publicPath
})
);
app.use(require("webpack-hot-middleware")(compiler));
// main route
app.get("/", (req, res) =>{
res.sendFile(path.resolve(__dirname, "./public/index.html"))
compiler.outputFileSystem.readFile(filename, (err, result) => {
if (err) {
return next(err);
}
res.set('content-type', 'text/html');
res.send(result);
res.end();
});
});
my package.json :
"scripts": {
"starter": "nodemon ./starter.js",
"start-dev": "concurrently --kill-others 'npm run webpack' 'npm run devserver'",
"devserver": "NODE_ENV=development nodemon ./server.js",
"webpack": "NODE_ENV=development webpack --w --hot --inline",
"start": "NODE_ENV=production webpack & NODE_ENV=production node ./server.js "
}
Any hint would be great,
Thanks
Related
I am requesting help setting up the compilation and dev environment for a typescript library. The library should work when consumed by a web app framework and when consumed by a script tag. I am currently using Webpack as a dev server so I can debug and TSC to build (cjs + esm). The issue that prompted this post was having to constantly switch my API strings between http://localhost:8080 to https://production.com. What tools or changes do I need in order to build dev and prod variables into my compilation?
Here is what I'm doing so far:
package.json fragment
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"files": [
"lib/**/*",
"README.md"
],
"scripts": {
"build:esm": "tsc -p tsconfig.json --outDir lib/esm --module ES2020 --sourceMap false",
"build:cjs": "tsc -p tsconfig.json --outdir lib/cjs --module commonjs --sourceMap false",
"clean:build": "rimraf lib",
"clean:serve": "rimraf dist",
"build": "rimraf lib && npm run build:esm && npm run build:cjs",
"serve": "rimraf dist && webpack-dev-server"
}
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const SRC = path.resolve(__dirname, 'src')
const ENTRTY = path.resolve(__dirname, 'src', 'debug.ts')
const DIST = path.resolve(__dirname, 'dist')
module.exports = {
mode: 'development',
context: SRC,
entry: ENTRTY,
output: {
path: DIST,
filename: 'index.js',
},
devtool: 'source-map',
devServer: {
contentBase: DIST,
writeToDisk: true,
host: '0.0.0.0',
port: 8080,
https: true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin()
],
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
include: [SRC]
}
]
}
}
My toolchain does not currently allow me to do do this:
import Axios from 'axios'
import SocketIO from 'socket.io-client'
export const axios = Axios.create({
baseURL: process.env.SERVER_HTTP_URL, //<-- can't do env-vars with tsc build
withCredentials: true
})
typescript cant not do that, but gulp can do it
const replace = require('gulp-replace');
const { src, dest } = require('gulp');
exports.default = function() {
return src(['*.js'], {base: './'})
.pipe(replace('__XXXX__', 'some variables'))
.pipe(dest('./'));
}
I am setting up my webpack config for a react app. But I am not able to reduce the size of bundle.js. In development mode the size is around 4MB and in production mode the size is around 1.5MB. Here is my config:-
const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
var config = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: [/.css$/],
use:[
'style-loader',
'css-loader'
]
},
{
test: /\.(png|jpg|gif|jpeg|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/images'
}
}
]
}
]
},
devtool: 'source-map',
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
filename: 'bundle.js'
},
devtool: 'source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: 'index.html'
})
],
devServer: {
contentBase: './dist',
hot: true,
port: 3000,
historyApiFallback: true
}
}
module.exports = (env, argv) => {
if (argv.mode === 'development') {
config.plugins = config.plugins.concat([
new BundleAnalyzerPlugin(),
])
}
if (argv.mode === 'production') {
config.plugins = config.plugins.concat([
new CleanWebpackPlugin(),
])
}
return config;
}
Please help me out in reducing the size of bundle.js. Thanks in advance :)
Refer: Bundle size in dev mode
Refer: Bundle size in prod mode
Script to run dev webpack-dev-server --config ./webpack.config.js --mode development --open --hot
Script to run prod webpack --config ./webpack.config.js --mode production --open --hot
Try adding
new DefinePlugin({
'process.env.NODE_ENV': JSON.stringify("production"),
}),
under plugins. React specifically eliminates a lot of debug code if you set that. Other libs may or may not look for it.
This is possibly rolled into the newish mode option, the docs have changed a bit since I last looked.
Bundle size 3.11MB in dev doesn't look too bad.
To further descrease the bundle size in production:
perform bundle minification
remove source maps
compress the bundle using gzip and Brotli and then let clients choose the compression
What I'm trying to achieve is to create a separate webpack assets file for copying static assets from the src folder to the web folder.
node version: 8.15.0
yarn version: 1.13.0
webpack: 4.19.1
copy-webpack-plugin: 6.0.0
To start, I already have a webpack.common.js file which deals with all the js files, and I have created the assets file, which can be seen below.
When I run
webpack --config=webpack/webpack.assets.js --mode development --progress --color
or
webpack --config=webpack/webpack.config.js --config=webpack/webpack.assets.js --mode development --progress --color --env development
I get this error ERROR in Path must be a string. Received undefined and I can't figure it out where it comes from.
By the way I just started dealing with webpack recently.
webpack.common.js
const webpack = require('webpack');
const path = require('path');
const PATHS = {
src: path.join(process.cwd(), 'src', 'js'),
dist: path.join(process.cwd(), 'web', 'js')
};
module.exports = {
entry: {
homepage: path.resolve(PATHS.src, 'pages/homepage.js'),
otherfile: path.resolve(PATHS.src, 'pages/othefile.js'),
}
output: {
path: PATHS.dist,
filename: '[name].js',
chunkFilename: '[name].js',
publicPath: '/js/'
},
...
}
webpack.assets.js
const webpack = require('webpack');
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const PATHS = {
src: path.join(process.cwd(), 'src', 'svg'),
dist: path.join(process.cwd(), 'web', 'svg')
};
module.exports = (env) => {
const svgFormat = env === 'production' ? '[name].[hash].[ext]' : '[name].[ext]';
return merge(commmonConfig, {
entry: [
path.resolve(PATHS.src, 'logo1.svg'),
path.resolve(PATHS.src, 'logo2.svg')
],
output: {
path: PATHS.dist
},
module: {
rules: [
{
test: /\.(svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: svgFormat,
},
},
],
},
]
},
plugins: [
new CopyPlugin([
{
from: PATHS.src,
to: PATHS.dist,
force: true,
toType: 'dir'
},
{
copyUnmodified: true,
debug: 'debug'
}
])
]
});
};
What I would like is to be able to run the assets commands with no errors, as the actual files get copied correctly.
Any ideas are very much appreciated!
You have passed your options object as a second pattern.
Move it outside of the patterns array and pass it as the second parameter instead:
plugins: [
new CopyPlugin(
[
{
from: PATHS.src,
to: PATHS.dist,
force: true,
toType: 'dir'
}
],
{
copyUnmodified: true,
debug: 'debug'
}
)
]
You get the error as your options object is being treated as a pattern but does not have a from property.
I am new in reactjs. I tried to configure react with basic index page including index.js(containing a console.log()) but when i tried to run server index.html showing properly but bundle.js is not loading. I search it a lot but not getting proper answer can any one help me please.
my webpack.config.js is
// Webpack config js.
var webpack = require("webpack");
var path = require("path");
var DIST_VAR = path.resolve(__dirname, "dist");
var SRC_VAR = path.resolve(__dirname, "src");
var config = {
entry : SRC_VAR + "\\app\\index.js",
output: {
path: DIST_VAR + "\\app\\",
filename: "bundle.js",
publicPath : "\\app\\",
},
module: {
rules: [
{
test: /\.js?/,
include: SRC_VAR,
loader: "babel-loader",
query: {
presets: [ "react" , "es2015" , "stage-2"]
}
}
]
}
};
module.exports = config;
Error is showing in console: Loading failed for the with source “http://localhost:8080/app/bundle.js”.
Edit:
Folder Listing added..
Folder PATH listing
Volume serial number is BE9C-4E51
C:.
| package-lock.json
| package.json
| webpack.config.js
|
+---dist
| | index.html
| |
| \---app
| bundle.js
|
+---node_modules
| <Here the node_modules>
\---src
| index.html
|
\---App
index.js
I'll make some assumptions without seeing your project folder structure.
Looks like it could be your publicPath. Unless that's what you intended, the /app folder shouldn't be visible and since your console is showing "localhost:8080/app/bundle.js" that means it's looking for "project-root/src/app/app/bundle.js" instead of "project-root/src/app/bundle.js"
In the webpack docs they're telling you to default to root '/' and looking at my own webpack file thats what mine is currently set to as well.
Reference:
https://webpack.js.org/guides/public-path/
Edit: Here's an example using Webpack 3. Version 4 just came out and this will not work, so I'd be careful where you're getting your config examples from if you are using Webpack 4.
const webpack = require('webpack');
const path = require('path');
module.exports = {
plugins: [
// new webpack.NamedModulesPlugin(),
// new webpack.HotModuleReplacementPlugin()
],
context: path.join(__dirname, 'src'),
entry: [
// 'webpack/hot/dev-server',
// 'webpack-hot-middleware/client',
// 'babel-polyfill',
// 'history',
'./index.js'
],
output: {
path: path.join(__dirname, 'www'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot-loader/webpack', 'babel-loader']
}],
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
},
};
after installing
npm init -y
and
npm install --save-dev webpack webpack-dev-server webpack-cli
and your structure files
src/
build/
webpack.config.js
package.json
go to package.json, and add build command:
"scripts": {
"start":"webpack serve --mode development",
"build":"webpack"
},
in webpack.config.js
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, './src/index.js'),
output: {
path: path.resolve(__dirname, './build'),
filename: 'bundle.js',
},
devServer: {
contentBase: path.resolve(__dirname, './build'),
},
};
so,in your build/index.html
<script type="text/javascript" src="./bundle.js"></script>
I recently changed the name of my root directory (where package.json and webpack.config.js sits) and now webpack-dev-server is not updating anytime I change my files.
Here's my webpack config:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/init.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
}
}
]
},
output: {
path: __dirname + "/src/",
filename: "app.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
devServer: {
port: 3000,
hot: true,
historyApiFallback: {
index: 'index.html'
}
}
};
And my directory looks like this (Client React is the folder that had its name changed):
Let me clarify that this worked fine before, so I really have no idea why this isn't working now.
Edit: Scripts in package.json
"scripts": {
"dev": "./node_modules/.bin/webpack-dev-server --content-base src --inline --hot",
"build": "webpack"
},
You have to remove the brackets. Probably because they are not properly escaped by the watch module that webpack uses (watchpack) or the part that does the final watching in the System itself. I recommend you don't use any special characters inside directory- or filenames because of such bugs.