webpack - Multiple entry and outputs with same structure but different directories? - javascript

I am relatively new with webpack and I was wondering if it is possible to have multiple entries and outputs with the same folder structure but in different directories. Let's suppose I have this structure:
application
views
scripts
docs
file1.js
file2.js
company
cp1.js
cp2.js
and I want to output in this directory/structure:
public
js
build
docs
file1.js
file2.js
company
cp1.js
cp2.js
Actually, my webpack.config.js is like this:
entry: {
app: path.resolve(__dirname, 'application', 'views', 'scripts', 'file1.js'),
app2: path.resolve(__dirname, 'application', 'views', 'scripts', 'file2.js'),
},
output: {
path: path.resolve(__dirname, 'public', 'js', 'scripts'),
filename: '[name].bundle.js'
}
but I do not want to specify individual entries for all js files and it's outputting in the wrong directory. Is it possible?

Here is the sample webpack.config.js code which would generate the required structure.
const glob = require('glob');
const path = require('path');
function getEntries(pattern) {
const entries = {};
glob.sync(pattern).forEach((file) => {
const outputFileKey = file.replace('application/views/scripts/', '');
entries[outputFileKey] = path.join(__dirname, file);
});
return entries;
}
module.exports = {
entry: getEntries('application/**/*.js'),
output: {
path: __dirname + '/public/js/build',
filename: '[name]',
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
resolve: {
extensions: ['.js'],
},
};

Related

Script Path for CSS and Bundle is a bit off after WebPack Creates index.html

For some reason, webpack is trying to append client to the href of the script tags for my CSS and bundle. The problem with this is that it's wrong. And I don't know how to tell it to trim that part off.
Before moving to webpack, here is how it looks in production when I was building it with Gulp:
notice above how everything was rooted from within the client folder. You don't even see the client folder because I think expressJS said to start from that point so you only see the root of what's in client such as lib, scripts, etc.
here's what the dist directory looked like when I was using Gulp for that:
Here's how I'm serving my static assets. My ExpressJS server sets the root folder for static asses as dist/client. This has always been the case even when I was using Gulp:
.use(
express.static('dist/client', {
maxage: oneYear,
})
)
Forward to now: It's using my new webpack.config now
Here is a Screenshot of dist from IDE as it is now after using webpack:
But now the index.html is gened by webpack:
<!doctype html><html lang="en"><head><title>My Title</title><meta charset="utf-8"><link href="https://ink.global.ssl.fastly.net/3.1.10/css/ink.min.css"><script src="https://ink.global.ssl.fastly.net/3.1.10/js/ink-all.min.js"></script><script src="https://ink.global.ssl.fastly.net/3.1.10/js/autoload.js"></script><link href="../client/lib/assets/css/main.c09764908684c2f56919.css?c09764908684c2f56919" rel="stylesheet"></head><body><div id="app"></div><script src="../client/scripts/app.c09764908684c2f56919.bundle.js?c09764908684c2f56919"></script></body></html>
webpack.config.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const isProduction = process.env.NODE_ENV === 'production';
const html = () => {
return new HtmlWebPackPlugin({
template: './src/client/index.html',
filename: './client/index.html',
hash: true,
});
};
const copyAllOtherDistFiles = () => {
return new CopyPlugin({
patterns: [
{ from: 'src/client/assets', to: 'client/lib/assets' },
{ from: 'src/server.js', to: './' },
{ from: 'src/api.js', to: './' },
{ from: 'package.json', to: './' },
{ from: 'ext', to: 'client/lib' },
{ from: 'feed.xml', to: 'client' },
{
from: 'src/shared',
to: './shared',
globOptions: {
ignore: ['**/*supressed.json'],
},
},
],
});
};
module.exports = {
entry: './src/client/index.js',
output: {
filename: 'client/scripts/app.[hash].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
target: 'web',
devServer: {
writeToDisk: true,
},
devtool: 'source-map',
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
splitChunks: {
cacheGroups: {
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
enforce: true,
},
},
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
},
{
test: /\.less$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['url-loader'],
},
],
},
plugins: isProduction
? [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: isProduction
? 'client/lib/assets/css/main.[hash].css'
: 'main.css',
}),
html(),
copyAllOtherDistFiles(),
]
: [new CleanWebpackPlugin(), html(), copyAllOtherDistFiles()],
};
Notice for my bundle the src generated includes ../client/ and same for my href for the CSS script.
The problem with this is that my app is served from the root of the client folder in dist. You'd think that ../client/ or ./client/ or client/ would work but it doesn't. When I run the site I get this because it can't find the bundle:
As you can see below, everything it stemming from context of the client folder already in the browser:
(what's also odd about this after moving to webpack, is why do I see a client folder if I told ExpressJS to start from the client folder already? When I was using the same exact code with Gulp, I did not see a client folder because I was already in it from the context of the browser)
So when I change the generated index.html manually in my dist folder, just to see if I can fix it, it all resolves just fine (notice I changed it to just lib/ and scripts/):
</script><link href="lib/assets/css/main.c09764908684c2f56919.css?c09764908684c2f56919" rel="stylesheet"></head><body><div id="app"></div><script src="scripts/app.c09764908684c2f56919.bundle.js?c09764908684c2f56919"></script></body></html>
The problem is I don't know how to get webpack to strip out that ..client/ part of the url when it gens the index.html. I've tried adding a publicPath property with '/', or './' or '' but no luck so far.
In other words this does not load: http://localhost:8080/client/scripts/app.b4b3659d9f8b3681c26d.bundle.js
but this does:
http://localhost:8080/scripts/app.b4b3659d9f8b3681c26d.bundle.js
http://localhost:8080/lib/assets/css/main.b4b3659d9f8b3681c26d.css
I think as long as you just write your output assets to same folder with the public folder set at your server, then it would work. Assuming the client will still be the public:
.use(
express.static('dist/client', {
maxage: oneYear,
})
)
I suggest to set entire output as client dir along side with its publicPath in webpack config for client:
output: {
filename: 'scripts/app.[hash].bundle.js',
path: path.resolve(__dirname, 'dist/client'),
publicPath: '/'
}
with the setting above, we don't have to specify the folder the html template location:
new HtmlWebPackPlugin({
template: path.resolve(__dirname, 'src/client', 'index.html'),
filename: 'index.html',
hash: true,
});
I don't quite understand yet why this fixed it but here is what made it work.
Definitely didn't need the publicPath:
output: {
filename: 'scripts/app.[hash].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
Changed my static path to be:
.use(
express.static('dist', {
maxage: oneYear,
})
)
move index.html out of the client folder and into the root of dist:
return new HtmlWebPackPlugin({
template: path.resolve(__dirname, 'src/client', 'index.html'),
filename: 'index.html',
hash: true,
});
Same with my bundle
output: {
filename: 'scripts/app.[hash].bundle.js',
publicPath: '/',
path: path.resolve(__dirname, 'dist'),
},
Same with assets:
patterns: [
{ from: 'src/client/assets', to: 'lib/assets' },
I don't see what moving it to the root of dist makes any difference but for some reason rendering / requesting to process index.html from the root of dist instead of dist/client works`

How do you fix "ERROR in Path must be a string. Received undefined" in webpack4/copy-webpack-plugin

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.

webpack - output.filename error

I know this is a common question for webpack; it's really hard to debug something if it won't give you any information about the cause or location of the error.
I'm getting the error:
Error: 'output.filename' is required, either in config file or as --output-filename
I know it has to do with a syntax error somewhere, but I'm too new to webpack to figure it out.
Here's my config file. It's called "webpack.config.js" in the root folder (i.e. the folder in which I initially ran: npm init).
const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const RewriteImportPlugin = require("less-plugin-rewrite-import");
const root_dir = path.resolve(__dirname)
const src_dir = path.resolve(__dirname, "webpack_src")
const build_dir = path.resolve(__dirname, "webpack_bin")
const node_mod_dir = path.resolve(__dirname, 'node_modules');
const extractLESS = new ExtractTextPlugin('style.css');
const config = {
entry: {
index: path.resolve(src_dir, 'index.js')
},
output: {
path: build_dir,
filename: 'bundle.js'
},
resolve: {
modules: [root_dir, 'node_modules'],
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.(js)$/
},
{
use: extractLESS.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'less-loader',
options: {
paths: [root_dir, node_mod_dir],
plugins: [
new RewriteImportPlugin({
paths: {
'../../theme.config': __dirname + '/semantic_ui/theme.config',
}
})
]
}
}]
}),
test: /\.less$/
},
{
use: ['file-loader'],
test: /\.(png|jpg|gif|woff|svg|eot|ttf|woff2)$/
},
]
},
plugins: [
extractLESS,
new webpack.optimize.ModuleConcatenationPlugin()
]
};
module.exports = {
config
};
You're exporting module.exports = { config }, which means that you are exporting an object with one property, namely config, but webpack expects the object to be your entire config. Webpack requires output.filename, whereas you only provide config.output.filename.
The export should be your config:
module.exports = config;

How to chunk the bundle.js file?

I have created a project using react and flux architecture. Need to chunk the bundle.js file because by combining all the files it is creating a huge js file of 4mb which is causing problem in downloading on slow network so how to chunk the js file so that only the required libraries are included when a page opens
I am using webpack 1.x
my directory structure is
webpack.config.js file
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-source-map',
entry: [
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: ''
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin({
// names: ["app", "subPageA"]
// (choose the chunks, or omit for all chunks)
children: true,
// (use all children of the chunk)
async: true,
// (create an async commons chunk)
// minChunks: 3,
// (3 children must share the module before it's separated)
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}, {
test: /\.css$/,
exclude: /\.useable\.css$/,
loader: "style-loader!css-loader"
}, {
test: /\.useable\.css$/,
loader: "style-loader/useable!css-loader"
}, {
test: /\.png$/,
loaders: ["url-loader?mimetype=image/png"]
}, {
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}]
}
};
server.js file
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', function(err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:3000/');
});
index.html file
<html>
<head>
<title>Project</title>
</head>
<body>
<div id="app" />
<script src="bundle.js" type="text/javascript"></script>
</body>
</html>
When you need a particular module, that is not required on the initial load you can use
require.ensure(["module-a", "module-b"], function() {
var a = require("module-a");
// ...
});
That way it only gets loaded when you need it, thus decreasing your bundle size.
If you use routes and react-router you can use per route code splitting as described in this article
http://moduscreate.com/code-splitting-for-react-router-with-es6-imports/
Im my experience, typically with webpack-optimize-chunk-plugin, you split your projects code into a vendor.js and a bundle.js. like this:
module.exports = {
entry:{
vendor: ["react", "react-dom"], // list all vender libraries here
app: ['./path/to/entry.js']
},
output: {
path: path.join(__dirname, './public'),
filename:'bundle.js'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js")
]
}
So this would output a bundle.js and a vendor.js. I haven't seen webpack-optimize-chunk-plugin used in the way you described. (it would be very cool if possible).
Also I would check out all the other webpack optimization plugins to also help with the over all file size. (i.e. DedupePlugin, UglifyJsPlugin, OccurenceOrderPlugin...). More info here. Also here is an example of multi entry point that you may find helpful. Best of luck.

Watch all Less Files but only compile one main one

So I downloaded a theme that has a bunch of less files but there is a main one that imports the others in the correct order. It came with a gulp file that watches any .less file but recompiles only the one that imports all the others. It looks like so:
gulp.task('less', function () {
return gulp.src(Paths.LESS_TOOLKIT_SOURCES)
.pipe(sourcemaps.init())
.pipe(less())
.pipe(autoprefixer())
.pipe(sourcemaps.write(Paths.HERE))
.pipe(gulp.dest('dist'))
})
My webpackconfig so far looks like the following:
// Things I still need to do:
// 1) Add uglifier plugin for minification
var path = require('path');
var webpack = require('webpack');
var cssnext = require('cssnext');
var cssimport = require('postcss-import');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var isProd = process.env.NODE_ENV === 'production' ? true : false;
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/index'
],
stylePath: path.resolve(__dirname, 'app', 'style'),
postcss: function () {
return [
cssimport({
path: './app/style/index.css',
onImport: function (files) {
files.forEach(this.addDependency)
}.bind(this)
}),
cssnext()
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
cssFilename: 'style.css',
publicPath: '/static/'
},
plugins: [
new ExtractTextPlugin('style.css', {
allChunks: true
}),
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'app')
},
{
test: /\.css$/,
loader: isProd ? ExtractTextPlugin.extract('style', 'css? modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss') : 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'
},
{
test: /\.less$/,
loader: "style!css!less"
}]
},
resolve: {
root: path.resolve(__dirname),
extensions: [
'',
'.js',
'.css'
],
modulesDirectories: [
'app',
'node_modules'
]
}
};
I am trying to accomplish the the same thing but with webpack. I have installed and setup the less-loader like the guide says but it tries to compile all of the files. Is there a way to set it up like the gulp file that will watch any file but only compile a specific file? I have this working in brunch when working in Phoenix but I trying to switch brunch out with webpack for phoenix.
In brunch I just told it to ignore the folder with the less files and then had the main less file outside that directory so brunch would only compile the main less file and import the others.

Categories