配置Webpack不要将JS文件捆绑在一起

时间:2016-06-16 23:21:44

标签: webpack

我正在使用Webpack生成两组JS包,一组在客户端运行,另一组在服务器上运行。对于服务器,我希望Webpack不要像这样捆绑任何文件:

source/
  entry-point.js  # requires component.js
  component.js

webpack-output-for-server/
  entry-point.js
  component.js

这样,当我运行webpack-output-for-server/entry-point.js并可能在component.js中遇到异常时,文件名将保留在堆栈跟踪中,而不依赖于源映射。它也更容易查看生成的源代码,而不必查看一个大包。

同样在Electron应用程序中,我不需要将JS文件捆绑在一起,因为Electron以与require()相同的方式定义CommonJS实现。我仍然希望使用Webpack来实现热重新加载等功能,但不希望它将文件捆绑在一起。

那么,有没有办法告诉Webpack不要捆绑文件,并保留他们的文件名?

2 个答案:

答案 0 :(得分:0)

webpack的主要工作是捆绑javascript,因此如果要维护单独的文件,则应使用gulp按照注释中的建议复制文件。但是,webpack能够创建commonjs2捆绑包,该捆绑包可以从服务器require输入。如果您的webpack配置使用了babel转换,css modules或节点本身无法理解的其他webpack功能等功能,您可能希望使用此功能。

为了使用它,您将需要两个webpack配置,一个用于服务器,一个用于客户端。在webpack中,这是通过导出数组而不是对象来实现的。

例如:

var serverConfig = {
    entry : './source/entry-point',
    output : {
       path: './webpack-output-for-server/',
       library: 'your-app-name',
       libraryTarget: 'commonjs2',
       filename: 'your-app-name.js'
    },
    module : {
      ...
    }
};

var browserConfig = {
    entry : './source/entry-point',
    output : {
       path: './public/',
       filename: 'bundle.js'
    },
    module : {
      ...
    }
};

module.exports = [
    serverConfig,
    browserConfig,
];

这将输出您的应用程序的两个副本,一个将捆绑用于浏览器,但另一个将捆绑为可由节点使用的独立commonjs2模块。我从未尝试过将它用于Electron,但它可能会有效。

答案 1 :(得分:0)

Mobius提供的答案没有错。但是,我建议你看一下GitHub上提供的一些流行的模板项目,包括https://github.com/RickWong/react-isomorphic-starterkit这个特殊的模板很受欢迎,并且有很多活动。

Webpack配置位于configs文件夹中。他们所做的是在两个文件夹中创建两个单独的配置,它们是通过package.json中定义的脚本同时构建的。

"scripts": {
  "start": "forever --minUptime 1000 --spinSleepTime 1000 -c \"node --harmony\" ./dist/server.js",
  "build-server": "webpack --colors --display-error-details --config configs/webpack.server.js",
  "build-client": "webpack --colors --display-error-details --config configs/webpack.client.js",
  "build": "concurrently \"npm run build-server\" \"npm run build-client\"",
  "watch-server": "webpack --watch --verbose --colors --display-error-details --config configs/webpack.server-watch.js",
  "watch-server-start": "node node_modules/just-wait --pattern \"dist/*.js\" && npm run start",
  "watch-client": "webpack-dev-server --config configs/webpack.client-watch.js",
  "watch": "concurrently --kill-others \"npm run watch-server-start\" \"npm run watch-server\" \"npm run watch-client\""
}

除了客户端和服务器脚本包之外,您还可以在此模板中找到许多其他功能,这些功能确实有助于开发。关键脚本是npm run watch,它将运行开发服务器,以便您可以看到更改。

相关问题