【发布时间】:2015-07-06 20:03:32
【问题描述】:
我一直在尝试将 webpack 与 nodejs 应用程序一起使用,并且客户端运行良好 - 他们网站上有相当不错的文档 + 来自谷歌搜索的链接。
有人在 nodejs 的服务器端使用过 webpack 吗?或者请引导我到任何有用的链接。
谢谢。
【问题讨论】:
我一直在尝试将 webpack 与 nodejs 应用程序一起使用,并且客户端运行良好 - 他们网站上有相当不错的文档 + 来自谷歌搜索的链接。
有人在 nodejs 的服务器端使用过 webpack 吗?或者请引导我到任何有用的链接。
谢谢。
【问题讨论】:
这是我在 Nodejs 应用程序中使用的 webpack 配置,当我希望它读取 JSX 时,如您所知,Node 无法做到。
const path = require('path');
module.exports = {
// inform webpack that I am building a bundle for nodejs rather than for the
// browser
target: 'node',
// tell webpack the root file of my server application
entry: './src/index.js',
// tells webpack where to put the output file generated
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
// tells webpack to run babel on every file it runs through
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [
'react',
'stage-0',
['env', { targets: { browsers: ['last 2 versions'] } }]
]
}
}
]
}
};
在你实现这个之后,不要忘记前往你的 package.json 文件并包含这个脚本:
{
"name": "react-ssr",
"version": "1.0.0",
"description": "Server side rendering project",
"main": "index.js",
"scripts": {
"dev:build:server": "webpack --config webpack.server.js"
},
【讨论】:
我想强调与客户端配置的区别:
target: 'node'
externals: [nodeExternals()]
对于node.js,捆绑node_modules/没有多大意义
output.libraryTarget: 'commonjs2'
没有这个,你不能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]
【讨论】:
for node.js, it doesn't make much sense to bundle node_modules/-这是因为它在服务器上运行,我们不需要担心捆绑我们的代码来减少请求的数量?在这里学习...谢谢。
it's running on the server and we don't need to worry about bundling our code to reduce the number of requests 是正确的。另一个原因是,如果某些库同时存在于“node_modules/”和您的包中,则会出现重复代码。
target: 'node' 设置,所以我可以捆绑一个快速服务器,并将前端和后端捆绑包用于生产用途。你会说这是这个配置选项的典型用法吗?
这可能有用:http://jlongster.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'
}
【讨论】:
output 部分添加 libraryTarget : "commonjs" 才能工作