我一直在尝试将webpack与nodejs应用程序一起使用,客户端方面还好——他们网站上有相当不错的文档以及来自谷歌搜索的链接。
有没有人在nodejs服务器端使用过webpack?或者请指引我到任何有用的链接。
谢谢。
这可能会有用: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'
}
我想要强调与客户端配置的不同之处:
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]
target: 'node'
这个设置,这样我就可以将一个Express服务器捆绑起来,并为生产环境将前后端捆绑在一起进行Docker化。你认为这是典型的配置选项使用方式吗? - 1252748这是我在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"
},
output
部分中添加**libraryTarget : "commonjs"
**才能正常工作。 - drodsou