I am new to webpack and have followed the quick start guide to create and process a simple js file from src to dist. All fine.
However now I am trying to get it to process more than one JS file but have hit a problem I can't find a way around. The file from the original tutorial still processes fine into dist, however a new JS file I have created does create a file into dist, but it is empty. The JS is not being minified into the dist.
So when running the below. /dist/scripttwo.js is fine..
HOWEVER, /dist/scriptone.js is always just an empty file.
webpack.config.js
const path = require('path');
module.exports = {
entry: {
scriptone: './src/scriptone.js',
scripttwo: './src/scripttwo.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
};
scriptone.js
function sayhello() {
return 'hello again';
}
scripttwo.js
import _ from 'lodash';
function component() {
const element = document.createElement('div');
// Lodash, currently included via a script, is required for this line to work
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
That is because you are not exporting or importing anything to scriptone.js.
to test:
export sayhello from scriptone.js add the following to end of file:
export defalut sayhello
and in scripttwo.js import the function and use it inside the file:
import _ from 'lodash';
import sayhello from './scriptone.js';
function component() {
const element = document.createElement('div');
// Lodash, currently included via a script, is required for this line to work
element.innerHTML = _.join(['Hello', 'webpack'], ' ') + sayhello();
return element;
}
document.body.appendChild(component());
The code will be there if you use mode: "development" configuration.
By default, Webpack uses production mode, Webpack v4+ will minify and tree shaking your code by default in production mode. The code in scriptone.js does nothing, has no side effects, it's dead code, Webpack will drop it. That's why you get an empty dist/scriptone.js bundle file.