问题描述
我试图将我的Rust代码编译为Wasm,并在Webpack附带的TypeScript项目中使用它。不幸的是,其中一个Rust依赖项需要导入的JS模块(crypto
),该模块在运行时找不到:
Error: Cannot find module 'crypto'
at webpackEmptyContext (webpack:///./pkg_sync?:2:10)
at Module.__wbg_require_604837428532a733 (webpack:///./pkg/index_bg.js?:589:58)
at __wbg_require_604837428532a733 (/[...]/dist/index.js:30:102)
at null.<anonymous> (wasm://wasm/005fd016:0:1161256)
at null.<anonymous> (wasm://wasm/005fd016:0:1109856)
at null.<anonymous> (wasm://wasm/005fd016:0:1211859)
at null.<anonymous> (wasm://wasm/005fd016:0:1191593)
at wasm_rand_r (wasm://wasm/005fd016:0:1070495)
at Module.wasm_rand_r (webpack:///./pkg/index_bg.js?:375:67)
at Object.eval (webpack:///./src/js/index.ts?:219:63) {
code: 'MODULE_NOT_FOUND'
}
我已经挖掘并得出结论,问题可能是在require
中使用wasm-bindgen
的方式:
export const __wbg_require_604837428532a733 = function(arg0,arg1) {
var ret = require(getStringFromWasm0(arg0,arg1));
return addHeapObject(ret);
};
所需的模块名称是getStringFromWasm0
的结果,据我所知Webpack无法处理动态模块名称。显然,当我手动放置var ret = require('crypto')
时,它就像一个超级按钮。
出于绝望,我试图通过将模块立即导入我的crypto
中来迫使Webpack将index.ts
包括在捆绑软件中:
import * as crypto from 'crypto' / const crypto = require('crypto')
但没有成功,错误仍然存在。
为了完整起见,这是我的webpack.config.js
:
const copyWebpackPlugin = require('copy-webpack-plugin')
const WasmPackPlugin = require('@wasm-tool/wasm-pack-plugin')
const path = require('path')
module.exports = {
entry: path.resolve(__dirname,'src/js/index.ts'),target: 'node',output: {
path: path.resolve(__dirname,'dist'),filename: 'index.js',libraryTarget: 'commonjs'
},resolve: {
extensions: ['.js','.ts'],modules: [path.resolve(__dirname,'node_modules')],descriptionFiles: [path.resolve(__dirname,'package.json')],symlinks: false
},module: {
rules: [
{
test: /\.ts$/,loader: "awesome-typescript-loader"
},{
test: /\.js$/,loader: "source-map-loader"
}
]
},plugins: [
new copyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname,'package.json'),to: path.resolve(__dirname,'dist')
}
]
}),new WasmPackPlugin({
crateDirectory: __dirname,outName: 'index',forceMode: 'production'
})
]
};
有没有办法让它与当前设置一起使用?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)