希望达成
1、使用ESM方式引入npm package
2、使用上直接import 引入
方式一:来自mpx(vue+webpack)的例子举例,
createPage({
onLoad() {
console.log('onLoad')
this.wasmPromise = import('@honwhy/urlsafe-base64')
.then((wasm) => {
console.log('wasm => ', wasm)
this.wasm = wasm
})
.catch((err) => console.error('Failed to load wasm module' + err))
},
data: {
wasmPromise = null,
wasm = null
}
})
..
处理方式上要打开webpack.experiments等特性,在vue.config.js中设置
module.exports = defineConfig({
// runtimeCompiler: true,
/**
* 如果希望node_modules下的文件时对应的缓存可以失效,
* 可以将configureWebpack.snap.managedPaths修改为 []
*/
// configureWebpack(config) {},
configureWebpack: {
experiments: {
futureDefaults: true,
asyncWebAssembly: true
}
},
}
...
方式二:最后像写web一样,首先由webpack或者vite处理好wasm加载问题
下面是vite+svelte的例子: github.com/honwhy/urlsafe-base64/webapp
<script type="module">
import {encode, decode} from '@honwhy/urlsafe-base64';
let orig = '';
let result = '';
let type = 'encode/decode';
function handleEncode(event) {
if(!orig) {
return false;
}
type = 'encode';
result = encode(orig);
console.log('encode result', result);
}
function handleDecode(event) {
if(!orig) {
return false;
}
type = 'decode';
try {
result = decode(orig);
} catch(e) {
result = 'decode error';
}
}
</script>
<main>
<h1>urlsafe-base64 demo</h1>
<div class="compo">
<div class="compo-item">
<textarea bind:value={orig}/>
<div>{type}:</div>
<textarea disabled bind:value={result}/>
</div>
<div class="compo-item">
<button on:click={handleEncode}>encode</button>
<button on:click={handleDecode}>decode</button>
</div>
</div>
</main>
问题现状
1、小程序支持的npm方式是cjs的,使用的关键字是require
https://developers.weixin.qq.com/miniprogram/dev/devtools/npm.html
2、WXWebAssembly像WebAssembly,需要指定确认的路径,但是npm 依赖中使用不太方便
https://developers.weixin.qq.com/miniprogram/dev/framework/performance/wasm.html