Use vite/rollup.js to extend the os module of Node.js
P粉176151589
2023-08-24 16:17:55
<p>I'm working on a Vite project that uses the <code>opensea-js</code> package. This package depends on <code>xhr2-cookies</code>, which imports <code>os</code>, <code>http</code>, <code>https</code> and others Some internal node modules. </p>
<p>When I try to call any opensea method, I get the following error: </p>
<pre class="brush:php;toolbar:false;">Uncaught (in promise) TypeError: os.type is not a function
XMLHttpRequest2 xml-http-request.ts:102
prepareRequest httpprovider.js:61
sendAsync httpprovider.js:116
node_modules opensea-js.js:24209</pre>
<p>Trace this error and find that it comes from building the user agent string. </p>
<p>I tried installing <code>rollup-plugin-polyfill-node</code> and adding it to <code>vite.config.js</code> but I still get the same error: < ;/p>
<pre class="brush:php;toolbar:false;">import path from 'path'
import vue from '@vitejs/plugin-vue'
import nodePolyfills from 'rollup-plugin-polyfill-node'
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
server: {
port: 8080,
},
define: {
'process.env': {},
},
build: {
rollupOptions: {
plugins: [
nodePolyfills(),
],
},
},
})</pre>
<p> I also tried manually repairing the file using <code>patch-package</code> which resolved the <code>os</code> error, but it failed when trying to send the request (because it uses polyfill<code>http</code>/<code>https</code> module). </p>
I used
rollup-plugin-polyfill-node
to solve this problem.Here is a more complete solution based on Fabiano's answer:
In my project, I used the following configuration to solve the problem. I describe the solution in a short article.