如何防止webpack捆绑包?

时间:2016-04-09 15:42:04

标签: webpack sequelize.js

我在我的webpack项目中使用Postgres和Sequelize。我遇到了一个错误列表,似乎webpack试图捆绑sequelize或postgres(pg)包:

ERROR in ./~/pg/lib/connection.js
Module not found: Error: Cannot resolve module 'net' in /Users/dace/Code/personal/my_project/node_modules/pg/lib
 @ ./~/pg/lib/connection.js 1:10-24

ERROR in ./~/pg/lib/connection.js
Module not found: Error: Cannot resolve module 'tls' in /Users/dace/Code/personal/my_project/node_modules/pg/lib
 @ ./~/pg/lib/connection.js 78:14-28

ERROR in ./~/pg/lib/native/index.js
Module not found: Error: Cannot resolve module 'pg-native' in /Users/dace/Code/personal/my_project/node_modules/pg/lib/native
 @ ./~/pg/lib/native/index.js 1:13-33

ERROR in ./~/pg/lib/connection-parameters.js
Module not found: Error: Cannot resolve module 'dns' in /Users/dace/Code/personal/my_project/node_modules/pg/lib
 @ ./~/pg/lib/connection-parameters.js 2:10-24

ERROR in ./~/pgpass/lib/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/dace/Code/personal/my_project/node_modules/pgpass/lib
 @ ./~/pgpass/lib/index.js 4:9-22

在我的webpack的dev.config.js文件中,我有:

var path = require('path');

module.exports = {
  entry: path.join(__dirname, '..', 'src', 'index.js'),
  output: {
    publicPath: '/build/',
    path: path.join(__dirname, '..', 'dist', 'build'),
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.js?$/,
        exclude: /node_modules/,
        loader: ['babel'],
        query: {
          presets: ['react', 'es2015'],
        },
      },
    ],
  },
};

然后在我的index.js中我有:

var Sequelize = require('sequelize');

var connection = new Sequelize('dev', 'dace', 'root', {
  dialect: 'postgres',
});

var Article = connection.define('article', {
  name: Sequelize.STRING,
})

connection.sync().then(function() {
  Article.create({
    name: 'Dace'
  });
});

我猜我需要保持webpack不会尝试捆绑sequelize或pg,因为当我从项目中完全删除webpack时它会起作用。有没有办法我可以配置webpack忽略在我的应用程序中捆绑这些包?

谢谢!

1 个答案:

答案 0 :(得分:3)

您不应该使用客户端代码中处理数据库,文件系统等的任何内容。例如fs模块(即filesystem)是仅在node环境中定义的内容,浏览器没有任何线索,fs可能是什么。 net也是如此(在浏览器中实现方式不同或根本没有实现)。难怪webpack对此感到困惑:)

我的建议:将代码重写为客户端,服务器和公共部分;确保客户端和服务器部件只在节点/浏览器环境中做有意义的事情。