I need to webpack all the js file in the script folder.I tried this
module.exports = {
module: {
loaders: [
{
test: /\\.js$/,
ex
The entry
value should resolve to a specific file, or a list of specific files.
From the webpack docs:
If you pass a string: The string is resolved to a module which is loaded upon startup.
If you pass an array: All modules are loaded upon startup. The last one is exported.
If you are simply trying to define one module, edit your entry
value to point to your main application file and then require other modules from that.
If you really want to bundle all files from a directory, see arseniews answer
I had some problems with file paths in Webpack 2.4.1, so made this. In addition to multiple entries, this also creates multiple .html files.
const HtmlWebpackPlugin = require('html-webpack-plugin');
const fs = require('fs');
function getEntries (){
return fs.readdirSync('./src/pages/')
.filter(
(file) => file.match(/.*\.js$/)
)
.map((file) => {
return {
name: file.substring(0, file.length - 3),
path: './pages/' + file
}
}).reduce((memo, file) => {
memo[file.name] = file.path
return memo;
}, {})
}
const config = {
entry: getEntries,
output: {
path: resolve('./public'),
filename: '[name].js'
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
filename: '[name].html',
template: './pages/_template.html'
})
]
}
Webpack is expecting a list of files for the entry
configuration, not a glob pattern.
You'll have to list the files manually, or automatically with this code snippet
var fs = require('fs'),
entries = fs.readdirSync('./src/scripts/').filter(function(file) {
return file.match(/.*\.js$/);
});
and then pass it to webpack's config.
Having one or few entry points should be enough for most of use cases, but if you really want to bundle up all files from directory you can use following:
As explained here: https://github.com/webpack/webpack/issues/370
var glob = require("glob");
// ...
entry: glob.sync("./src/scripts/*.js")
Just using glob.sync
will result in sequential filenames, such as 0.[hash].js
and 1.[hash].js
, because entry
expects an object with the the name of the file in the key and its location in the value, but glob.sync
returns an array.
The following method has the benefit of producing an object with keys and values based on the filenames, you can also add additional entries, such as vendor
and common
. Requires lodash.
const glob = require("glob");
const _ = require('lodash');
module.exports = {
entry: Object.assign({},
_.reduce(glob.sync("./src/*.js"),
(obj, val) => {
const filenameRegex = /([\w\d_-]*)\.?[^\\\/]*$/i;
obj[val.match(filenameRegex)[1]] = val;
return obj;
},
{}),
{
vendor: [
'lodash'
]
}
),
output: {
filename: '[name].[chunkhash].bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
The latter will produce the following object and pass it to entry
, provided we have index.js
and app.js
in the ./src
directory:
{
index: './src/index.js',
app: './src/app.js',
vendor: [ 'lodash' ]
}