So we are in the middle of adding Vitest to an existing project that currently relies on Webpack for bundling our code. We are in the process of rewriting older jQuery code into React.
Right now i’m running into problems because our current project is set up in a way where Node Module libraries like ‘polyglot’ and ‘jQuery’ are exposed globally to the entire application window. (IE window.polyglot or window.jQuery)
. This was pretty easy to set up in Webpack using the expose-loader
plugin.
I’m pretty new to Vite and Vitest and have been pouring over the docs to try and understand the best way to accomplish this.
When trying to render one of our React components called <Footer />
in a test that uses a global library called Polyglot for language translation stuff I see this error.
ReferenceError: Polyglot is not defined
❯ src/webhfs/i18n.js:269:18
267| const _XLATE_PHRASES = Object.freeze(/*<XLATE_PHRASES>*/ {});
268|
269| const polyglot = new Polyglot({
| ^
270| phrases: _XLATE_PHRASES,
The library it is complaining about comes from node_modles/node_polyglot
and I pull it into our application in Webpack like so.
{
test: require.resolve("node-polyglot"),
loader: "expose-loader",
options: {
exposes: ["Polyglot"]
},
},
So I’m trying to replicate how to do this in Vitest.
From reading the docs I thought it had something todo with creating an alias
like so.
export default defineConfig({
define: {
Polyglot: true
},
resolve: {
alias: {
"Polyglot": './node_modules/node-polyglot',
}
},
test: {
globals: true,
environment: "jsdom",
setupFiles: "./test.setup.ts",
css:true,
}
})
But this didn’t work as expected either, it just gives me a new and different error.
TypeError: Polyglot is not a constructor
So I’m looking for some direction on where to start with this. What am I not understanding about vitest and globals in the window such as this.
Thanks so much in advance.