How do I manually include "#material/drawer" into my component? - javascript

I am trying to manually include the #material/drawer npm package into my Ember app. I tried following this guide but I'm running into some weird errors in my Chrome dev console:
Uncaught SyntaxError: Unexpected token *
Uncaught ReferenceError: define is not defined
The first is from the imported node_modules/#material/drawer/index.js file and the second is from my generated shim.
My component code:
import Component from '#ember/component';
import { MDCTemporaryDrawer, MDCTemporaryDrawerFoundation, util } from '#material/drawer';
export default Component.extend({
init() {
this._super(...arguments);
const drawer = new MDCTemporaryDrawer(document.querySelector('.mdc-drawer--temporary'));
document.querySelector('.menu').addEventListener('click', () => drawer.open = true);
}
});
In my ember-cli-build.js:
app.import('node_modules/#material/drawer/index.js');
app.import('vendor/shims/#material/drawer.js');
My generated shim:
(function() {
function vendorModule() {
'use strict';
return {
'default': self['#material/drawer'],
__esModule: true,
};
}
define('#material/drawer', [], vendorModule);
})();
What exactly am I doing wrong? It almost seems as though raw ES6 code got imported rather than compiled into my JS build output.
I also read this SO post but there are too many answers and I'm not sure which to do. It seems this specific answer is what I'm trying to do but not verbatim enough.

Creating a shim only ensures that ember-cli gets an AMD module, which you then can import in your app files.
If the npm package needs a build or transpiling step beforhand, this won't work.
You need a way to get the package build within the ember-cli build pipeline.
Luckily there are addons which can take care of this for you: ember-auto-import and ember-cli-cjs-transform.
You may have also heard of ember-browserify, which does the same thing, but it's deprectaed in favor of ember-auto-import.
I'd suggest you try ember-auto-import:
ember install ember-auto-import
You then should be able to import as you tried:
import { MDCTemporaryDrawer, MDCTemporaryDrawerFoundation, util } from '#material/drawer';
No shim or app.import needed, as ember-auto-import will take care of this for you.

Related

Cannot use newly installed plugins (node modules) in Nuxt pages/components

First off, I'm a beginner with NuxtJS and front-end development in general, so it might be that I'm missing something - though I do believe I went through all the options before posting here. Apologies in advance if that is not the case.
I've been having trouble using installed modules that I've registered as plugins. For example, take mapbox-sdk.
After installing it with npm install #mapbox/mapbox-sdk, which correctly creates #mapbox/mapbox-sdk in node_modules, I register it in nuxt.config.js:
plugins: [
...
"~/plugins/mapbox-sdk.js",
],
Of course, I also create the mapbox-sdk.js file in plugins/, containing:
import "#mapbox/mapbox-sdk";
Then, in a page (say, myMap.vue), when I try:
var mapboxClient = mapboxSdk({ accessToken: MY_ACCESS_TOKEN });
which is the basic usage example in the documentation, I get:
mapboxSdk is not defined
in the console. This behavior extends to every single module I installed today, but is not the case for modules I had previously installed.
The reason why you're getting the error mapboxSdk is not defined is because there are a few issues with the way you've set up this plugin.
Docs here https://nuxtjs.org/docs/2.x/directory-structure/plugins/, they have some useful diagrams.
There are a couple of ways you can use this package.
Plugin
// ~/plugins/mapbox-sdk.js
import mapboxSdk from '#mapbox/mapbox-sdk'
export default (_ctx, inject) => {
// Exposing the mapboxSdk to your Nuxt app as $mapBox.
inject('mapBox', mapboxSdk)
}
Then in nuxt.config.js, same as you've already done.
plugins: [
...
"~/plugins/mapbox-sdk.js",
],
Then in your component myMap.vue
var mapboxClient = this.$mapBox({ accessToken: MY_ACCESS_TOKEN });
Directly in the component:
If you don't wish to use a plugin, the way that #kissu mentioned above https://stackoverflow.com/a/67421094/12205549 will also work.
Try adding this after the import to let Vue know that this method exists (in the same .vue file) at first
<script>
import mapboxSdk from '#mapbox/mapbox-sdk'
export default {
methods: {
mapboxSdk,
},
mounted() {
console.log('mapbox function >>', mapboxSdk)
},
}
</script>
Do you have it working in a .vue component at first ?

Vue 3 component incorrectly initialized when module is `npm link`ed

Following is the entry point to my library, it generates a component with a dynamic tag:
// muvement.js
import { defineComponent, ref, onMounted, h } from 'vue';
const createMuvement = (tag) => {
return defineComponent({
name: `m-${tag}`,
setup(props, context) {
const root = ref(null);
onMounted(() => {
console.log(root.value);
});
return () => h(tag, { ...context.attrs, ref: root }, context.slots);
}
});
};
const muvement = (...tags) => {
const components = {};
tags.map((tag) => (components[`m-${tag}`] = createMuvement(tag)));
return components;
};
export { muvement };
It's expected to be consumed like so:
// Home.vue
<template>
<div>
<m-div>div</m-div>
<m-button>button</m-button>
</div>
</template>
<script>
import { muvement } from "muvement";
export default {
name: "Home",
components: {
...muvement("div", "button")
}
};
</script>
This works as expected when the library code is contained within the Vue app folder (assuming we are now importing from "#/components/muvement.js" instead of "movement").
That is:
-muvement-test-project (scaffolded with vue-cli)
- src
- views
- Home.vue
- components
- muvement.js
I've also published an alpha release that works fine when importing "muvement" after installing it directly from the npm registry (that is, npm install muvement instead of npm link muvement).
The Problem
During development, I want an app to test the library with that is separate from the library's directory.
I've used npm link to link the library to the test app (as I have done with many other projects in the past).
From /path/to/library
$ npm link
From /path/to/test/app
$ npm link muvement
So far so good. The module is available as a symlink in the test app's node_modules folder. So I import { muvement } from "muvement", run npm run serve, and... BOOM.
Everything explodes (see errors below). It's also probably worth noting that trying to import from the full path (i.e. C:/dev/npm/muvment/dist/es/index.js) results in the same issues as npm link does, so I don't think it has anything to do with the symlink directly.
This is what appears in the console:
For pretty much the entire day I have been trying to solve this one issue. I've seen several seemingly similar questions that were solved by settings Webpack's resolve.symlinks to false but that has no effect on my problem. I've read all through the docs and even Vue's source code (here is the offending line for those who are curious).
Since the warning suggests that the error is commonly attributed to async setup I thought maybe webpack was doing something weird that would make my code async. This doesn't seem to be the case as the call stack of both the working attempt and failed attempt are identical.
What's not identical is the scope.
Here is the scope for the example that is working:
And here is the failing one:
(Notice that the target parameter is null during the call to injectHook, which is obviously what prompts Vue to show a warning).
My question is, why does the location of the imported module make such a difference during the execution of the said module?
The library code and build setup are available here:
https://github.com/justintaddei/muvement
The test app is available here:
https://github.com/justintaddei/muvement/tree/example
If I've left out something important, please let me know in the comments. It's been a long day so I'm sure I've probably missed something.
Thank you.
The problem is your app is using two different vue dependencies under the hood - vue requires the same dependency to be used to keep track on reactivity, lifecycle, etc.
When you link a library npm/yarn will use that linked folder node_modules, but your app is using it's dependencies from it's node_modules.
When your app imports vue it will go app/node_modules/vue but when you import from your linked dependency it will be going to linked_dep/node_modules/vue.
app
node_modules
vue
linked library
node_modules
vue
One easy way to debug this issue is to change both vue dependency files with a console.log and check if the console is logging both.

How to setup the DfxParser in Angular

I want to use https://github.com/gdsestimating/dxf-parser in my project. When i import in like:
import { DxfParser } from 'dxf-parser';
and than call:
new DxfParser()
i get an error:
TypeError: dxf_parser__WEBPACK_IMPORTED_MODULE_3__ is not a
constructor
What would be the correct way to use the DxfParser in angular? I want to do the same in angular as the jaascript example on projects site:
var parser = new DxfParser();
try {
var dxf = parser.parseSync(fileText);
}catch(err) {
return console.error(err.stack);
}
thanks a lot!
Like the readme of the github states, did you install DxfParser?
npm install dxf-parser
You might also need to install the types for typescript like so:
npm install #types/dxf-parser
Since installing does not seem to be the problem I tried it myself. Doing the import like you did does not work. I looked into the code and it seems that DxfParser is a default export. So if you do:
import DxfParser from "dxf-parser";
It should be working.
More information on exports can be found here

Mocha keeps bombing due to absolute paths

I'm having a great deal of trouble using Enzyme and Mocha to test my React project. I have a test like this:
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import { ChipInput} from '../client/components/Chips';
describe('<ChipInput />', _ => {
it('rocks', done => {
done();
});
});
And when ChipInput gets imported, that file imports something with an absolute path, e.g. /lib/collections/tags, and then Mocha errors out because it apparently only does relative paths. How do I get this working?
EDIT:
The actual error:
Error: Cannot find module '/lib/collections/tags'
This happens because /tests/ChipInput-test.js imports the ChipInput component from /client/components/Chips/index.js, which has the following lines:
import React from 'react';
import {
MapsLocalOffer as TagIcon,
ImageRemoveRedEye as InsightIcon,
EditorInsertChart as TestIcon,
SocialPerson as UserIcon,
} from 'material-ui/svg-icons';
import { Tag } from '/lib/collections/tags'; // error thrown here
import { Insight } from '/lib/collections/insights';
// import { Test } from '/lib/collections/tests';
import Chip from './Chip';
import ChipDisplay from './ChipDisplay';
import ChipInput from './ChipInput';
import * as chipTypes from './chip-types';
To anyone hitting here from google, while ffxsam's answer will work, there are many ways to accomplish this. Node's require allows for a base to be set either via environment variable or programmatically, allowing for simple absolute paths that don't require the leading slash (require("my/module"); vs require("/my/module");).
I use gulp as a taskrunner, so my preferred technique is to use app-module-path to do the following at the top of my gulpfile (this will work anywhere, so long as you haven't encountered any absolute requires yet):
require('babel-core/register'); //for mocha to use es6
require('app-module-path').addPath(__dirname + '/src'); //set root path
//I also use webpack to pull in other extensions, so I
//want mocha to noop out on them
require.extensions['.css'] = _.noop;
require.extensions['.scss'] = _.noop;
require.extensions['.png'] = _.noop;
require.extensions['.jpg'] = _.noop;
require.extensions['.jpeg'] = _.noop;
require.extensions['.gif'] = _.noop;
For a more complete rundown, check out this gist by github user branneman: https://gist.github.com/branneman/8048520
This has been awhile, but I want to share my solution here, just in case, all solutions above don't work in your specific situation. I was looking for a solution to fix our unit test, which failed "Error: Cannot find module 'components/shared/xyz', our 'components' folder is under 'client/src' folder, so I came up with the following solution which works for us.
npm install babel-plugin-module-resolver --save-dev
{
'plugins': [
'babel-plugin-module-resolver',
{ 'root': ['client/src'] }
]
}
Here's the solution, nice and simple!
https://github.com/mantrajs/babel-root-slash-import
Basically, install said package:
npm install babel-root-slash-import --save-dev
Add the plugin to .babelrc:
{
"plugins": [
"babel-root-slash-import"
]
}
And it's good to go.

Using ember-cli-sheetjs in an ember component

I'm creating a website using ember and am currently having difficulty using the 'ember-cli-sheetjs' module in a component titled 'add-student.js'. I cannot seem to call any functions in the documentation using my current code.
To get the module in ember I added it to my dev dependencies inside package.json and then ran the "npm install" command which successfully installed the "ember-cli-sheetjs" module. I then try and use it by writing:
import Ember from 'ember';
import xlsx from 'npm:ember-cli-sheetjs';
//have also tried directly using the sheetjs module after
//installing sheetjs with the command
//npm install xlsx --save-dev
//import xlsx from 'npm:xlsx';
export default Ember.Component.extend({
fileinput: null, //this is set with an input handler in the hbs
actions: {
fileLoaded: function() {
console.log(this.get('fileinput')); //properly outputs the file name
var workbook = xlsx.readFile(this.get('fileinput'));
},
}
However this results an error saying:
add-student.js:134 Uncaught TypeError: _npmEmberCliSheetjs.default.readFile is not a function
I feel like the problem is that its not following the correct path to the function (which exists in the function documentation). If anyone can tell me what I'm doing wrong it would be a huge help.
Link to the module: https://www.npmjs.com/package/ember-cli-sheetjs
If anyone runs into this problem I have figured out a work around.
First in your index.html include the line:
<script src="assets/parsing/dist/xlsx.full.min.js"></script>
Next create a folder inside public (if it doesn't already exist) called assets. Next create a folder inside assets called 'parsing' and a folder in 'parsing' called 'dist'. Next in 'dist' create a file called 'xlsx.full.min.js'.
Next copy and paste the code from: https://raw.githubusercontent.com/SheetJS/js-xlsx/master/dist/xlsx.full.min.js into the xlsx.full.min.js file.
Finally, in whatever component you want to use the sheetjs module in just put the following below your import statement:
/* global XLSX */
This is a work around but it does allow you to use the sheetjs module.
Use Bower
// bower.json
"dependencies": {
"js-xlsx": "^0.11.5"
}
// ember-cli-build.js
module.exports = function(defaults) {
app.import('bower_components/js-xlsx/dist/xlsx.min.js');
}
and in your component as #Russ suggested:
import Ember from 'ember';
/* global XLSX */

Categories

Resources