I've been trying to use webpack with a nodejs application, and the client side is going fine - a reasonably good documentation on their website + links from google search.
Has anyone used webpack on server side of nodejs? or please guide me to any useful links.
Thanks.
If you're trying to server-side render a frontend component that isn't in JavaScript, you'll need Webpack and plugins like vue-loader to compile the specialized syntax into JavaScript.
It's not necessary at all.js back-end. I'm not saying you can't or shouldn't set up a webpack-dev-server to develop your back-end code locally. But you definitely don't need to bundle your backend code on your build process. webpack bundles are meant for the browser.
Node. js is a JavaScript framework for writing server-side applications. In its simplest form it allows you to trigger small JavaScript programs from the command line without any browser involved. For example, assuming node is installed if you write a JavaScript program in a file called hello.
Being able to call Node. js modules from JavaScript running in the browser has many advantages because it allows you to use Node. js modules for client-side JavaScript applications without having to use a server with Node.
This might be useful: http://jlongster.com/Backend-Apps-with-Webpack--Part-I
Key point is to make external all third party module (in node_modules directory) in webpack config file
Final config file
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './src/main.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'backend.js'
},
externals: nodeModules,
plugins: [
new webpack.IgnorePlugin(/\.(css|less)$/),
new webpack.BannerPlugin('require("source-map-support").install();',
{ raw: true, entryOnly: false })
],
devtool: 'sourcemap'
}
I want to highlight the difference from client side config:
target: 'node'
externals: [nodeExternals()]
for node.js, it doesn't make much sense to bundle node_modules/
output.libraryTarget: 'commonjs2'
without this, you cannot require('your-library')
import nodeExternals from 'webpack-node-externals'
const config = {
target: 'node',
externals: [nodeExternals()],
entry: {
'src/index': './src/index.js',
'test/index': './test/index.js'
},
output: {
path: __dirname,
filename: '[name].bundle.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: [
['env', {
'targets': {
'node': 'current'
}
}]
]
}
}
}]
}
}
export default [config]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With