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>
Related
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;
}
I have a Preact project using Vite. I want to use the nexmo-client SDK from vonage but when I import using the ES method it breaks my project.
// app.tsx
import NexmoClient from 'nexmo-client';
I get the following error in the console.
index.js:19 Uncaught ReferenceError: global is not defined
at index.js:19:19
at index.js:12:22
at node_modules/nexmo-client/dist/index.js (index.js:16:1)
at __require (chunk-J43GMYXM.js?v=f3505250:11:50)
at dep:nexmo-client:1:16
However if I import it using via a script tag it works just fine.
// index.html
<script src="node_modules/nexmo-client/dist/nexmoClient.js"></script>
// app.tsx
const NexmoClient = window.NexmoClient;
OK, there are two problems here.
Firstly, NexmoClient tries to use global which is not available on the browser.
Secondly, NexmoClient has a dependency on socket.io-client, for some reason Vite imports a Node version of the socket.io-client that again tries to use modules that are not available on the browser, namely 'child_process'.
To fix both issues you can provide the following config to Vite, this should make sure the resulting build is compatible with the brother.
// vite.config.js or vite.config.ts
import { defineConfig } from 'vite'
import preact from '#preact/preset-vite'
export default defineConfig({
plugins: [preact()],
define: {
global: {},
},
resolve: {
alias: {
"xmlhttprequest-ssl": "./node_modules/engine.io-client/lib/xmlhttprequest.js"
}
}
})
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)
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
I am going through the Gatsby.js tutorial and in tutorial two, you have to import some fonts. When I try to import theme lawton I see this error under import lawtonTheme from "typography-theme-lawton";
I first did npm install --save typography-theme-lawton
Could not find a declaration file for module 'typography-theme-lawton'. '/Users/react/tutorial-part-two/node_modules/typography-theme-lawton/dist/index.js' implicitly has an 'any' type.
Try `npm install #types/typography-theme-lawton` if it exists or add a new declaration (.d.ts) file containing `declare module 'typography-theme-lawton';`
This is my typography.js file:
import Typography from "typography";
//import bootstrapTheme from " typography-theme-bootstrap";
import lawtonTheme from "typography-theme-lawton";
const typography = new Typography(lawtonTheme);
//const typography = new Typography({ baseFontSize: "18px" });
//const typography = new Typography(bootstrapTheme);
export default typography;
This is my gatsby-config.js file:
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography.js`
}
}
]
};
Also in the gatsby-config file, the word module is underline and this note shows:
[ts] File is a CommonJS module; it may be converted to an ES6 module. [80001]
I also tried npm install #types/typography-theme-lawton but it gave me errors
Based on your your problem,I guess you are using typescript, and the project can't find the ts module.
You need to install ts files.Try this:
npm install —-save #types/.....
Or, you can add a d.ts file in your project somewhere, and add the above in the file.
declare module typography-theme-lawton
[ts] File is a CommonJS module; it may be converted to an ES6 module. [80001]
I assume you are using VSCode.Add this in the setting to enable it:
"javascript.suggestionActions.enabled": false
PS: It's just a suggestion,so you can just ignore this.