Stats is not exported by node_modules error - Rollup - javascript

I'm trying to add stats.js ( a little fps counter ) to my three.js scene. The project uses rollup to bundle everything and I keep getting this error after trying to import Stats like so:
import { Stats } from 'stats.js'
The error reads:
[!] Error: 'Stats' is
not exported by node_modules\stats.js\build\stats.min.js, imported by src\main.js
My rollup config looks like this:
import resolve from '#rollup/plugin-node-resolve'; // locate and bundle dependencies in node_modules (mandatory)
import { terser } from "rollup-plugin-terser"; // code minification (optional)
export default {
input: 'src/main.js',
output: [
{
format: 'umd',
name: 'LIB',
file: 'build/main.js'
}
],
plugins: [ resolve(), terser() ]
};
Stats is exported in stats.js like this:
export { Stats as default };
I keep scrolling through bug reports on github and i'm unsure if they relate or not - getting confused - does anyone have a clue?
EDIT: based in the initial answer, I tried using:
import * as Stats from 'stats.js'
i get the error message:
Uncaught TypeError: Cannot set property 'Stats' of undefined
referencing this line:
(function(f,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"===typeof define&&define.amd?define(e):f.Stats=e();})(undefined,function(){var f=function(){function e(a){c.appendChild(a.dom);return a}function u(a){for(var d=0;d<c.children.length;d++)c.children[d].style.display=d===a?"block":"none";l=a;}var l=0,c=document.createElement("div");c.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000";c.addEventListener("click",function(a){a.preventDefault();
__
I tried:
const Stats = require('stats-js');
and got the error message:
Uncaught ReferenceError: require is not defined
__
I tried:
import Stats from 'stats-js'
and got this:
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
stats-js (imported by src\main.js)(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
stats-js (guessing 'Stats')
I sounds like this last error is the most useful? I followed the link in the error message but still can't fix it.

That library doesn’t provide an es6 default export.
import * as Stats from 'stats-js'
// or
const Stats = require('stats-js')
// or
import Stats from 'stats-js'

I had a similar error to yours, but I found the reason and used the following code when importing
import {} from 'Stats.js'
(sorry for using a translator)

Related

Import javascript from node_modules in angular

I installed a npm package which contains a javascript file, what I want to use. The js file name is all.js and contains this code:
import { initExtended } from './extended'
import Header from './components/header/header'
function initAll(options) {
// Set the options to an empty object by default if no options are passed.
options = typeof options !== 'undefined' ? options : {}
// Allow the user to initialise GOV.UK Frontend in only certain sections of the page
// Defaults to the entire document if nothing is set.
var scope = typeof options.scope !== 'undefined' ? options.scope : document
// Find first header module to enhance.
var $toggleButton = scope.querySelector('[data-module="govuk-header"]')
new Header($toggleButton).init()
initExtended(options)
}
export {
initAll,
Header
}
File all.js is located in node_modules.
When I tried to import it directly from index.html like:
<script type="module" src="node_modules/#id-sk/frontend/govuk/all.js"></script>
It is not working. Console error, file not found.
I also tried import it via angular.json:
"scripts": [
"./node_modules/#id-sk/frontend/govuk/all.js"
]
Also not working with error "Uncaught SyntaxError: Cannot use import statement outside a module (at scripts.js:15241:1)". The error refers to line:
import { initExtended } from './extended'
I also tried to import it in polyfills but I don't know how to call it.
As you are speaking about angular.json, I assume that you are working in an Angular application bootstrapped using the Angular CLI with default settings.
To be able to use this package #id-sk/frontend in your typescript files, you have to import it directly into your typescript file.
1. Import #id-sk/frontend in your TS files
// Import everything into a local variable
import * as govuk from '#id-sk/frontend';
// Import specific object
import { HeaderExtended } from '#id-sk/frontend';
2. Run ng serve
⚠ Spoil: It will lead to typings errors
3. Let's add or create typings
As #id-sk/frontend is not written in typescript, the compile doesn't know about the typings of this library.
Following this statement, you have two choices:
Find or contribute to DefinitelyTyped in order to create the typings of your package #id-sk/frontend
Create a local file typings.d.ts in your ./src folder to declare an empty module
declare module "#id-sk/frontend"
4. Kill & run ng serve again
Enjoy it!
Go further
You can add typings to your module in order to give you autocompletion on the provided objects of #id-sk/frontend.
``ts
declare module "#id-sk/frontend" {
export interface Options {
scope?: Document
}
export function initAll(options: Options): void;
}

Can't generate Nuxt website with #googlemaps/js-api-loader

I am using #googlemaps/js-api-loader in my Nuxt 3 website. Everything works fine in local development, but when I try to build the project with nuxt generate (no matter if locally or on Vercel) I'm getting following error:
[nuxt] [request error] Named export 'Loader' not found. The requested module 'file:///path/to/website/node_modules/#googlemaps/js-api-loader/dist/index.umd.js' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using:
The important part of loading script looks like this:
import { Loader } from '#googlemaps/js-api-loader';
const loader = new Loader({
apiKey: config.googleMapsApiKey,
version: 'weekly',
});
onMounted(async() => {
await loader
.load()
...
so I tried to import this package differently, e.g.:
import * as gmaps from '#googlemaps/js-api-loader';
const { Loader } = gmaps;
and the previous error disappeared, but now I'm getting
[Vue warn]: Unhandled error during execution of setup function
at <DynamicLocations class="contact__map" locations= [
{
id: 1,
...
[nuxt] [request error] gmaps.Loader is not a constructor
at setup (./.nuxt/prerender/chunks/app/server.mjs:5536:20)
at _sfc_main$t.setup (./.nuxt/prerender/chunks/app/server.mjs:5582:25)
at callWithErrorHandling (./.nuxt/prerender/chunks/renderer.mjs:2654:23)
at setupStatefulComponent (./.nuxt/prerender/chunks/renderer.mjs:9548:30)
at setupComponent (./.nuxt/prerender/chunks/renderer.mjs:9503:12)
at renderComponentVNode (./.nuxt/prerender/chunks/renderer.mjs:12068:17)
at Object.ssrRenderComponent (./.nuxt/prerender/chunks/renderer.mjs:12504:12)
at ./.nuxt/prerender/chunks/app/server.mjs:5628:36
at renderComponentSubTree (./.nuxt/prerender/chunks/renderer.mjs:12149:13)
at renderComponentVNode (./.nuxt/prerender/chunks/renderer.mjs:12084:16)
I also can't import package by default export. Do you have any ideas what's going on and how can I fix this?
I found a documentation page related to this problem and there is the following information:
If you encounter these errors, the issue is almost certainly with the upstream library. They need to fix their library to support being imported by Node.
Although they provide a solution to get rid of errors by adding the package to build.transpile:
build: {
transpile: ['#googlemaps/js-api-loader'],
},
It worked for me

How to use functions from different part of my code in jest testing?

I'm trying to write a test in jest.
I have 2 functions in a different js file that i need to use in order to pass
data to the function im testing.
i tried to use:
import {func} from './funcfile' gives:
SyntaxError: Cannot use import statement outside a module
const {func} = require('./funcfile') gives:
SyntaxError: Unexpected token 'export'
looking at other topics and google, tried every dependency installation and added configurations to package.json, jest.config.js, .babelrc, babel.config.js.
the only thing that happened is getting an error around type ErrorHandler = ...
where it says a syntax error again excepted ";"
i reverted everything therefore i don't have the files with the changes, willing to try any solution you may seem fit.
it crashes on export const phone_number and never event get to the getSubCategory export line....
Edit:
Been asked to add some more code so others could understand better,
Thing is there is not much more code.
I have a file with lots of export const = ;
(as described in photo)
and eventually the function export const (as described in photo)
on my jest file i just have the import/ require line I added and the test fails there.
the error i get when using the suggested answer :
You can import your utils class and use constants as properties of this exported module, e.g.
import * as UTILS from './utils';
...
UTILS.getSubCategoryId('return input')
where utils is
export const getSubCategoryId = (category) => category;
Please check example
https://stackblitz.com/edit/typescript-rujqvm?file=index.ts
Combined with VadimB solution had to add these lines to .babelrc on root directory
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Now its all up and working

VueJS compile failing when importing json data

I'm trying to import a static .json file in the <script> section of a .Vue file like so import Test from '#assets/test.json'
Based on what I've read about webpack, this should work out of the box. I've also tried explicitly defining both the .json extension in webpack resolve and the json loader under loaders.
However, for me it fails with the error:
ERROR Failed to compile with 1 errors 9:14:24 AM
This dependency was not found:
* #assets/test.json in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Settings.vue?vue&type=script&lang=js&
To install it, you can run: npm install --save #assets/test.json
That seems to be strange as it's not a dependency I'd be able to install?
My test.json file just contains {}, but I've also tried it with the real data file and the same outcome.
Thanks in advance for any help.
Edit: Thanks to #tao for helping me figure it out on chat. The error was indeed trivial: import Test from '#assets/test.json' should have been import Test from '#/assets/test.json'
For typescript support you have to add
"resolveJsonModule": true,
to compilerOptions in tsconfig.json.
And add
declare module '*.json' {
const value: unknown;
export default value;
}
to your shims-vue.d.ts
In Javascript, you don't need to do anything special. This should work:
test.json:
{
"foo": "bar"
}
Your *.vue SFC file:
<script>
import * as json from './test.json';
export default {
data: () => ({
json
}),
mounted() {
console.log(this.json)
}
}
</script>

Can't import vue2-google-maps component to main.js

After installing vue2-google-maps with npm, I'm trying to import the component to my main.js. But I keep getting an error. I never had problem importing packages to main.js or to other .vue files.
Versions:
vue 2.6.10
vue2-google-maps#0.10.7
vue-cli 2.9.6 but also tried with 3.11.0
import App from "./App.vue";
import store from "./store/store.js";
import * as VueGoogleMaps from "vue2-google-maps";
Vue.use(
VueGoogleMaps,
{
load: {
key: "AIzaSyBYULuuIqKYMJVrEk1PjpUDQQYkGMmP0iM",
libraries: 'places'
}
}
);
I'm getting the error in this line : import * as VueGoogleMaps from "vue2-google-maps";
Error Message: Could not find a declaration file for module 'vue2-google-maps'.
'c:/Users/BotiVegh/vueJS_projects/vue-store-gallery-map/node_modules/vue2-google-maps/dist/main.js'
implicitly has an 'any' type. Try npm install
#types/vue2-google-maps if it exists or add a new declaration (.d.ts)
file containing declare module 'vue2-google-maps';ts(7016)
Do I need to change something in the config file?
You could try adding "noImplicitAny": false to your tsconfig.json file
This disables warnings on expressions and declarations with an implied 'any' type

Categories