How to exclude directory from getting bundled by Webpack? - javascript

Expected:
When I build with webpack, all my JS files get bundled except for the files in the ./src/Portfolio directory as per my Webpack.config.js settings.
Actual:
Webpack bundles all the files including the ones in the directory despite the settings and other variations i have provided within webpack.config.js.
Code:
Webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [
{
test: /\.js$/,
exclude: [
path.resolve(__dirname, './src/Portfolio/')
]
}
]
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
Output:
How can i successfully exclude the ./src/Portfolio directory and its
contents?

Depending on what your folder structure looks like it appears you aren't providing it the right directory location to exclude. I would think something like this should work, but if not please share your folder structure.
const path = require('path');
module.exports = {
entry: './src/index.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [
{
test: /\.js$/,
exclude: [
'./src/Portfolio/'
]
}
]
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};

I know the op is using javascript, fyi a similar problem can occur using typescript with webpack.
In this case excluded directories can be added to tsconfig.json instead of webpack.config.js,
//tsconfig.json
{
"compilerOptions": {
...
},
"exclude": [
"./src/Portfolio/",
]
}

Related

Yarn watch, Can not get /

Im trying to get some server side rendering to work for my react project with yarn, webpack and babel. When I type in yarn watch in the terminal the program compiles correctly and then the localhost window appears, It says "Can not get /". This is because I need a output(I think), but I am unsure as in how to create one correctly.
here below is the code inside my webpack.config.js file:
const path = require("path");
module.exports = {
devServer: {
contentBase: path.resolve(__dirname, "./src" ),
historyApiFallback: true,
writeToDisk: true,
},
entry: path.resolve(__dirname, "./src/index.js" ),
module: {
rules: [
{
test: /\.js$/, exclude: /node_modules/, use:"babel-loader"
},
{
test: /\.css$/i,
use: ["css-loader"]
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
use: ["url-loader"]
},
]
},
output: {
path: __dirname + '/dist',
filename: "bundle.js"
},
};
The Bundle.js filename in the output was made in the public folder inside the index.html.
<script src="bundle.js"></script>
Sorry if this made no sense but I dont understand how this does not work correctly.

webpack-dev-server not recompiling the output file

This is my webpack file, nothing special
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'public/scripts'),
publicPath: '/public/scripts/',
filename: 'bundle.js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}]
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
watchContentBase : true,
publicPath: '/scripts/'
}
}
However, when I run 'npm run webpack-dev-server', I get the normal node.js output but the website does not update when new changes are made. I deleted the bundle.js file and when I ran it again, I got an error saying 'bundle.js cannot be found'. I figured out that bundle.js is not being recompiled at all when running this command.
I am on windows if that makes any difference. Any help would be appreciated.
EDIT: Below is my folder structure.
You need to use watchContentBase option for devServer:
watchContentBase:true
Would also recommend setting hot:true for modules replecement and open:true - so when you will run the dev server it will automatically open you your site at default browser.
More on devServer options you could find here - https://webpack.js.org/configuration/dev-server/#devserverwatchoptions-
EDIT
So after quite long conversation in chat, here are the results:
Still to "live-reload" the page you should use watchContentBase
But there were other issues in this case - publicPath in devServer and outputPath were not the same and then index.html should reference bundle.js under /public/scripts
New webpack.config.js:
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, '/public/scripts'),
publicPath: '/public/scripts',
filename: 'bundle.js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}]
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
watchContentBase : true,
publicPath: '/public/scripts'
}
}
New src for bundle in Index.html:
/public/scripts/bundle.js

webpack-dev-server getting complied but no output file is created?

webpack-dev-server is getting compiled but not creating any output file while using simple webpack it is creating the file. Why?
const path = require("path");
module.exports = {
entry: "./src/app.js",
output: {
path: path.join(__dirname, "/public/"), //file path name
filename: "bundles.js" //this is not getting created
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_ modules/,
loader: "babel-loader" //loader
}
]
},
devtool: "cheap-module-eval-source-map",
devServer: {
contentBase: path.join(__dirname, 'public'),
compress: true,
port: 9000
}
};
It should create bundle.js
and it is not giving any compile time error as well it shows it's compiled successfully.
There's an option called writeToDisk
https://webpack.js.org/configuration/dev-server/#devserverwritetodisk-

How to export bundled libraries in my vendor.js (CommonsChunkPlugin)?

I have two webpack 2 projects
The 1st one, let's call it lib1 is a library of reusable React components. In the webpack config it is exported as a library with the name lib1. The project lists react and react-dom as external dependencies.
The 2nd one, let's call it proj1 is an app that uses lib1. Because lib1 is served on a cdn, it's listed as an external dependency. The project also depends on react and react-dom. Using CommonsChunkPlugin I generare a vendor.js that includes react and react-dom (and eventually other dependencies).
When I run proj1 in the browser, the code inside lib1 fails because it can't find react. The libraries are loaded in this order:
<script src="dist/vendor.js"></script>
<script src="http://cdn.com/lib1/lib1.js"></script>
<script src="dist/bundle.js"></script>
I guess the issue is that react and react-dom are not exported by my vendor.js file.
I tried using the library option like this (int proj1):
library: "[name]",
libraryTarget: "umd"
But it creates window.vendor not window.React and window.ReactDOM.
How do I do that?
lib1 config
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, "dist"), // string
filename: "bundle.js",
publicPath: "/dist/",
library: "lib1",
libraryTarget: "umd",
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: path.resolve(__dirname, "node_modules"),
}]
},
externals: ["react", "react-dom"],
};
proj1 config
var webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
bundle : './src/index.js',
vendor : ['react', 'react-dom']
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
publicPath: "/dist/",
library: "[name]",
libraryTarget: "umd",
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor'
})
],
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: path.resolve(__dirname, "node_modules"),
}]
},
externals: ["lib1"],
devtool: "source-map"
};

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