Using NPM packages client-side with nuxt - javascript

I'm very new to nuxt and javascript and I'm trying to figure out how to use my app's dependencies client-side. I have them listed in my nuxt.config.js and installed with npm. I also have a file in the /plugins directory that imports them (not sure if this is good or not). Here is where I run into trouble: I have two scripts located in my /static directory that need to take advantage of my npm packages. Putting an import statement in those scripts causes an error. Importing the packages in the script section of the page vue file also doesn't work. How can I use npm packages in scripts that are included in pages client-side?

Can you provide a more information, about which kind of error is happening and which kind of packages did you try to install?
In this example I am going to show you how I included in my nuxt project npm package vuelidate
after installing vuelidate:
add to nuxt.config.js
plugins: [
{ src: "~/plugins/vuelidate", mode: "client" },
],
create vuelidate.js file in my plugin folder (plugin/vuelidate.js)
import Vue from 'vue'
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate);
after that I can use vuelidate in my .vue components (no always necessary to import something because in our 2 stage Vue.use(Vuelidate) we already installed vuelidate globally)
<script>
import { required, minLength } from "vuelidate/lib/validators";
export default {
name: "OrderByLinkForm",
components: {},
...
};
</script>

Related

React: Trying to import a javascript file from node_modules from a package I have installed but cannot be recognised

I am trying to import a file from react-validation but I am met with the following warning which isn't allowing the import:
Could not find a declaration file for module
'react-validation/build/form'
This file does exist in my node_modules folder since I installed the package via npm i react-validation and I clearly see the folder is there.
I tried import in different ways, for example: import Form from 'react-validation/build/form but still not working.

Vue - Remove specific JavaScript files for production mode

I have lots of .js files to import in Vue components in my project. Some of these JavaScript files are meant to be used in development mode and they won't be included in production but I am not allowed to delete these files in project. For example;
There are two JavaScript files called authDev.js and authProd.js. Their usage is basically the same but their content are different from each other. Inside of these JavaScript files there are functions and I export them to be able to import in several Vue components.
The first question, If I dynamically export or import them, will webpack include these files when I run npm run build? In other words, let's say I created a JavaScript file but I didn't export it, so I didn't import it to anywhere either. Does webpack understand that this JavaScript file is not used in anywhere of these Vue project and discard it when it builds my project to production? Or does it include every single file that existed in the project?
The second question, is there a way to tell the webpack that those JavaScript files will not be included in dist folder these will... I mean, can I specify files for development and production?
First I thought I could import or export them based on a condition but when I try to put my imports in if statements, it gives me an error and says "imports must be at the top level". So I tried to export them dynamically but couldn't do it either.
Then I try to remove specific blocks of codes in files. There are packages and plugins to remove every console outputs from Vue projects but I couldn't find anything to remove or discard specific lines of codes.
At last, I decided to took a way to include and exclude specific files. Is there a way to do it? If it is, how do I do that? Thanks in advance.
THE SOLUTION (EDITED)
For a quick test, I created two .js files called auth-development.js and auth-production.js in src/assets/js/filename.js location. Here are the contents of them;
auth-production.js
export const auth = {
authLink: "http://production.authlink/something/v1/",
authText: "Production Mode"
}
auth-development.js
export const auth = {
authLink: "http://localhost:8080/something/v1/",
authText: "Development Mode"
}
Then I modified my webpack config which is in the vue.config.js file;
const path = require('path');
module.exports = {
configureWebpack: {
resolve: {
alias: {
'conditionalAuth': path.resolve(__dirname, `src/assets/js/auth-${process.env.NODE_ENV}.js`)
}
}
}
}
Vue was giving "path is undefined" error, I added the top part of the code to handle that error. I used process.env.NODE_ENV to get the words development and production to add the end of my javascript files so that I can define their path.
Then I dynamically imported this conditionalAuth to a test component called "HelloWorld" as follows;
<script>
import * as auth from 'conditionalAuth';
export default {
name: 'HelloWorld',
data(){
return {
auth: auth
}
}
}
</script>
And I used them like this;
<template>
<div>
<p>You are in the {{ auth.auth.authText}}</p>
<p>{{ auth.auth.authLink }}</p>
</div>
</template>
In this way when I npm run serve it imports auth-development.js but if I npm run build and try the index.html in the dist folder on a live server, it only imports the auth-production.js.
At last, when I check the final build, auth-development.js is not built for my dist version of the project. It only imports the production javascript file in the chunk.
Assuming the file names are: auth-development.js and auth-production.js, you can use webpack alias to import file according to environment.
resolve: {
alias: {
'conditionalAuth': path.resolve(__dirname, `path/to/js/auth-${process.env.NODE_ENV}.js`)
},
extensions: ['.js', '.vue', '.json']
}
then you should be able to import the desired file like:
import * as auth from 'conditionalAuth';

Is there a way to integrate stencil components into frameworks locally without publishing to NPM?

I am currently testing stencil js. For now I want to write stencil components and include them within a VUE/React project. The official website of stencil already shows how to integrate them within a framework (https://stenciljs.com/docs/overview). But they assume that your own stencil component library has already been published to npm.
Is there a way to integrate stencil components locally into a framework to test them without publishing them first?
Yes, you can use npm-link for that.
cd my-component-lib
npm link
cd ../my-app
npm link my-component-lib # or whatever you have named the project in package.json
If you have any problems with that (e. g. with paths not resolving properly), you can also try to pack your package and install the packed version instead, using npm-pack:
cd my-component-lib
npm pack
cd ../my-app
npm install ../my-component-lib/my-component-lib-1.0.0.tgz
Linking is preferable though because changes to your component library will be reflected immediately (after a rebuild), whereas with packing you'd have to re-pack and re-install it after every change to your lib.
Instead of publishing or packing your packages, you could utilize TypeScript's path mapping feature.
This allows you to write your import statements just as you would with a published package, but behind the scenes TypeScript maps the imports to their given source code location.
Here's an example of a tsconfig.json with path mapping added to the compiler options:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"ui-components": ["libs/ui-components"],
"ui-components/loader": ["libs/ui-components/dist/loader/index.cjs.js"],
"ui-components-react": ["generated/ui-components-react/src/components.ts"]
},
...
As you can see, it has 3 mappings: the path to the core Stencil components ui-components, the path to the generated React components which are exposed as ui-components-react, as well as the generated loader ui-components/loader which provides the bridge between the Custom elements and the React wrappers.
I created a full working example for Stencil Web Components with generated bindings and wrappers for React that comes without the need of publishing any package: Nx Stencil React.
Please note that this answer is based on #stencil/core 1.14.0 or below. Future versions may have a different approach on generating the framework integrations.
I've had quite a bit of trouble with this myself so will provide an answer specifically for Vue 3 as Stencil's Framework Integrations guide seems to refer only to Vue 2.
Starting Projects
Stencil Component
Following the Getting Started guide run npm init stencil. Choose the component option.
There was a bug in v2.7.0 so I update to v2.8.0 with npm i #stencil/core#latest --save-exact
Build the project with npm run build
Optional
By default, the stencil project configures multiple build targets, to make it easier to see what build files are being used you can edit the stencil config to only include the custom elements bundle:
\\ stencil.config.ts
outputTargets: [
{
type: 'dist-custom-elements-bundle',
},
{
type: 'dist',
esmLoaderPath: '../loader',
},
],
You also need the 'dist' type for the .d.ts typings file to be generated with your custom-elements (not sure why).
Vue 3 App
Using a globally installed Vue CLI #vue/cli#4.5.13 create a new Vue 3 default project.
Using Stencil in Vue 3
Install your stencil component project
npm install --save ../<path>/stencil-component as a dependency of your vue app.
Fixing NPM Module Resolution
Following the Vue CLI - Troubleshooting guide add a vue.config.js file to the root of your Vue 3 project with the line config.resolve.symlinks(false),
Skipping Component Resolution
In the same file we need to configure Using Custom Elements in View
\\ vue.config.js
module.exports = {
chainWebpack: (config) => {
config.resolve.symlinks(false),
config.module
.rule("vue")
.use("vue-loader")
.tap((options) => ({
...options,
compilerOptions: {
isCustomElement: (tag) => tag.includes("my-"),
},
}));
},
};
Framework Integration
Now we can declare the custom elements, but in the Vue 3 way
\\ main.js
import { createApp } from 'vue'
import App from './App.vue'
import { defineCustomElements } from "stencil-component";
defineCustomElements();
createApp(App).mount('#app');
You can now use your custom component as normal. Here's what my App.vue file looked like after hacking the example starter code:
<template>
<my-component first="Andy" middle="2K" last="11"></my-component>
</template>
<script>
import { MyComponent } from "stencil-component";
export default {
name: 'App',
components: {
MyComponent
}
}
</script>
Errors
No ESLint Config
No ESLint configuration found in /<path>/stencil-component/dist/custom-elements.
Fixed by telling webpack not to resolve symlinks in vue.config.js
Uncaught TypeError: class constructors must be invoked with 'new'
This error occurs in the browser after a successful compilation.
Resolved by telling webpack / vue not to resolve your custom components
Custom Component Not Visible
There are no errors and your component is showing in the DOM inspector but not appearing on the page.
You need to defineCustomElements() in main.js.
Component not found
I've had some variation of this error when trying to import and use my component but haven't been able to reproduce it just now. Doing all of the above and restarting the dev server works fine for me.
For local integration, you can reference the esm.js file inside www/build folder which can be used in the head tag of the Vue/React project.
For eg if you have the below 2 apps
stencil-components - stencil components
stencil-react - sample react app which will consume the components.
Once you run stencil-components by npm run start it will be hosted at 3333 (by default).
Including below line in head ofindex.html of stencil-react will integrate components with live reloading on change.
<script type="module" src="http://localhost:3333/build/stencil-components.esm.js"></script>

Applying loaders to files imported via resolve.modules in webpack

I have two javascript projects in separate directories within a parent directory and I want both of them to be able to import files from a common directory. The structure looks a bit like this:
- parentDir
- project1
- package.json
- webpack.config.js
- src
- index.js
- project2
- package.json
- webpack.config.js
- src
- index.js
- common
- components
- CommonComponent.vue
- application
- app.js
I'd like both project1's index.js and project2's index.js to be able to import CommonComponent.vue and app.js.
Currently this works if I do:
import CommonComponent from ../../common/components/CommonComponent.vue
However those import paths starts to get very messy and hard to maintain the deeper into each tree we go, with huge numbers of ../s, so I'm trying to find a way of making the imports neater and easier to manage and I came across resolve options in webpack. So I've tried adding this to my webpack.config.js:
resolve: {
modules: [
path.resolve("../common/"),
path.resolve("./node_modules")
]
},
so then the import would look like:
import CommonComponent from "components/CommonComponent.vue"
import app from "application/app"
Importing the plain js file works, but when trying to import the .vue file, webpack throws an error:
ERROR in C:/parentDir/common/components/CommonComponent.vue
Module not found: Error: Can't resolve 'vue-style-loader' in 'C:/parentDir/common/components'
So how can I apply webpack loaders to files imported via resolve.modules?
Note: importing .vue files from within a single project works fine, so my module.rules config is correct.
It turns out the common package needed its own node_modules. That doesn't seem to be the case when importing a file from there directly via its path, but it is when using either resolve.modules or resolve.alias in webpack.
So the answer was to npm init in common and then to npm install all the dependencies and devDependencies needed there. e.g (of course these will depend on the project):
npm install --save vue
npm install --save-dev babel-core babel-loader css-loader less-loader vue-loader vue-template-compiler webpack
Once that's done, both of these webpack configs seem to have the same result as far as I can tell:
resolve: {
modules: [
path.resolve("../../common"),
path.resolve("./node_modules")
]
},
and
resolve: {
alias: {
components: path.resolve("../../common/components")
}
}
Both allow a file in project1 or project2 to do an import like:
import CommonComponent from "components/CommonComponent.vue"

NodeJS require/import module from higher level directory

I am using node v9.2.0. Want to load module located in higher level directory.
Here is minimal example: https://github.com/skkap/es6importtest
Suppose I have following dir structure:
/common/
index.mjs
/app/
app.mjs
/node_modules/
package.json
index.mjs contains some logic and also imports some npm module, like graphql.
import graphql from 'graphql'
...
export default graphql
I want to import common/index.mjs module from app.js.
import common from '../common/'
And get the following error:
Error: Cannot find module graphql
Any ideas where the problem is?
I checked, it also works the same wat with require(): https://github.com/skkap/es6importtest/tree/master/requireTest
P.S. Please do not recommend using npm packages or webpack for that, this question is about the particular problem described above.

Categories