blog
blog copied to clipboard
nodejs c++ 非静态方法、资源打包问题
const path = require('path');
const webpack = require('webpack');
const { MergeIntoSingleFilePlugin } = require('webpack-merge-and-include-globally');
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
target: 'node',
mode: 'production',
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
plugins: [
new MergeIntoSingleFilePlugin({
files: {
'package.json': {
transform: (content) => {
const pkg = JSON.parse(content);
pkg.dependencies = {
...pkg.dependencies,
'@trustwallet/wallet-core': '^1.0.0',
};
return JSON.stringify(pkg, null, 2);
},
},
},
transform: (content, path) => {
if (path.endsWith('.ts') || path.endsWith('.js')) {
return `require(${JSON.stringify(path)});`;
}
return content;
},
ignore: ['@trustwallet/wallet-core'],
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
],
};
在使用webpack打包nodejs服务端代码时,如果遇到依赖底层c++模块的方法导致报错,可以采取以下几种处理方式:
- 使用externals配置项排除这些模块,让它们不参与打包。例如:
externals: {
'my-cpp-module': 'commonjs my-cpp-module'
}
- 将依赖底层c++模块的代码单独打包成一个模块,使用node-externals排除这个模块,然后在运行时动态加载这个模块。例如:
// webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
// ...
target: 'node',
externals: [nodeExternals({
allowlist: ['my-cpp-module']
})],
entry: {
server: './src/server.js',
cpp: './src/cpp.js'
},
output: {
// ...
filename: '[name].js'
}
};
// server.js
const myCppModule = require('./cpp');
// ...
// cpp.js
module.exports = require('my-cpp-module');
- 使用webpack-node-externals排除所有的node_modules模块,然后在运行时动态加载需要的模块。例如:
// webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
// ...
target: 'node',
externals: [nodeExternals()],
// ...
};
// server.js
const myCppModule = require('my-cpp-module');
// ...
以上三种方式都可以解决依赖底层c++模块的报错问题,具体使用哪种方式取决于具体情况。