在nodejs的服务器端使用webpack

use*_*865 36 node.js webpack

我一直在尝试使用带有nodejs应用程序的webpack,客户端也很顺利 - 他们的网站上有一个相当不错的文档+来自谷歌搜索的链接.

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

谢谢.

Oli*_*dov 25

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

关键点是在webpack配置文件中创建外部所有第三方模块(在node_modules目录中)

最终的配置文件

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'
}
Run Code Online (Sandbox Code Playgroud)

  • 出于某种原因,我不得不在`output`部分添加**`libraryTarget:"commonjs"`**让我工作 (2认同)
  • 那你怎么把"依赖"(而不是devDependencies)引入/ build/node_modules? (2认同)

Tyl*_*ong 20

webpack 2.x的一个真实示例

我想强调与客户端配置的区别:

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]
Run Code Online (Sandbox Code Playgroud)