我一直在尝试将webpack与nodejs应用程序一起使用,客户端也很顺利 - 他们网站上的文档相当不错+谷歌搜索链接。
有没有人在nodejs的服务器端使用webpack?或者请指导我任何有用的链接。
感谢。
答案 0 :(得分:24)
这可能很有用: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'
}
答案 1 :(得分:20)
我想强调与客户端配置的区别:
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]
答案 2 :(得分:0)
这是我在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"
},