在nodejs的服务器端使用webpack

我一直在尝试使用一个nodejs应用程序的webpack,而客户端也很好 – 在他们的网站+谷歌search链接相当不错的文档。

有没有人在nodejs的服务器端使用过webpack? 或者请指导我任何有用的链接。

谢谢。

这可能是有用的: http : //jlong​​ster.com/Backend-Apps-with-Webpack–Part-I

关键是要在webpackconfiguration文件中build立外部所有第三方模块(在node_modules目录下)

最终configuration文件

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' } 

一个webpack 2.x的例子

我想强调从客户端configuration的差异:

1. target: 'node'

2. externals: [nodeExternals()]

对于node.js,捆绑node_modules/

3. output.libraryTarget: 'commonjs2'

没有这个,你不能require('your-library')

webpack.config.js

 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]