Error using Materialize css with require - requirejs

I created a new project using durandal using its starter kit (http://durandaljs.com/get-started.html)
I then added materialize using bower (bower install materialze)
After adding materialize to require config of durandal
requirejs.config({
paths: {
'text': '../lib/require/text',
'durandal':'../lib/durandal/js',
'plugins' : '../lib/durandal/js/plugins',
'transitions' : '../lib/durandal/js/transitions',
'knockout': '../lib/knockout/knockout-3.1.0',
'bootstrap': '../lib/bootstrap/js/bootstrap',
'jquery': '../lib/jquery/jquery-1.9.1',
'hammerjs': '../lib/hammer/hammer',
'jquery.hammer': '../bower_components/materialize/js/jquery.hammer',
'materialize': '../bower_components/materialize/dist/js/materialize'
},
shim: {
'bootstrap': {
deps: ['jquery'],
exports: 'jquery'
},
'materialize': {
deps: ['jquery', 'hammerjs']
},
'jquery.hammer': {
deps: ['jquery', 'hammerjs', 'waves']
}
}
});
I end up in error -
Uncaught Error: Mismatched anonymous define() module: function ($, Hammer)
Actually, every time I refresh, I end up with different errors, which seems to point me to something messed up with require. My question is - if everything works rock solid before adding materialize, how does adding it make things so flaky?
Am I doing something wrong?

Your question is from 1 year, 9 months ago and now Materialize doesn't have jQuery as a dependency and I believe they no longer use hammer.js or they are about not to. Still this is something everybody runs into with Materialize and it is fixable!
First off, if you aren't in the habit of looking inside of your node_modules I encourage you to take a look and see if you can find hammer.min.js (I believe it is in the bundle you would have in 2016) or hammer.js because as soon as you can if you start looking at other people's source you will learn stuff faster. Some of these problems arise because you can install modules globally or locally and you gotta manage all the versions and it just goes on and on but this is the fun of npm and node package managers.
**
Quick Answer Begins Here:
**
Bower is deprecated but this issue effects you similarly if you use npm in 2018 and it would in theory help people using bower. You need to include the javascript dependencies (note that jQuery became optional recently with the release of version 1.0.0)
Example 1
This is what I do if I've installed my npm modules locally and I am making an electron application:
you are going to have the same problem with CSS so in foo.html you want:
<link href="./node_modules/materialize-css/dist/css/materialize.css" rel="stylesheet">
in bar.js you want:
window.Hammer = require('./node_modules/materialize-css/js/hammer.min.js')
Example 2:
I install my modules globally and want to pull in Materialize maybe I use grunt or webpack and in this contrived example im using jquery-2.1.4.min.js
In foo.js
window.$ = window.jQuery = require('../assets/jquery/jquery-2.1.4.min.js');
window.Hammer = require('../assets/hammer/hammer.min.js');

Related

How do I set up parsely with nodejs?

I've been working on form validation for days. I'm trying to validate a multi step form.
I'm using Nodejs, ES6, Express, PUG. I'm having a hard time finding something that works. I think parsley would do it for me, but I cant get it to work with NodeJS.
For the code in my .js file (Where risk-calc is the id of my form):
$('.form-navigation .next').click(function() {
if ($('#risk-calc').parsley().validate({group: 'block-' + curIndex()}))
navigateTo(curIndex() + 1);
My console error is '$(...).parsley is not a function.'
I've installed via NPM parselyjs and jquery.
edit.
Attempting to use webpack to add global variables.
Something is still wrong, but how does this look?
plugins: [
new ExtractTextPlugin('style.css'),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
parsley: 'parsleyjs/dist/parsley.js'
}),
You will need to include the parsely javascript code after you include the jquery code. That will then extend the jquery object to have the parsely method.
If you have imported both through npm then you will need import the parsleyjs module at the top of your main entry file for you javascript before bundling it. I would recommend using webpack for the bundling.
import 'parsleyjs'
Usually jQuery can be added to your project files globally through the webpack provide plugin.
See: https://webpack.js.org/plugins/provide-plugin/
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})

Mocha - Running test ReferenceError: regeneratorRuntime is not defined

I am trying to run tests with async/await using mocha. The project architecture was setup before I started working on it and I have been trying to update it's node version to 8.9.4. The project is an isomorphic application and uses babel, gulp and webpack to run.
To run the tests we run a gulp task. There are two .bablerc files in the project. One in the root folder of the project and another in the test fodler.
Both have the same configuration:
{
"presets": [
["env", {"exclude": ["transform-regenerator"]}],
"react",
"stage-1"
],
"plugins": [
"babel-plugin-root-import"
]
}
When I run the app locally there is no error returned anymore. However when I run the tests with gulp test:api I constantly get the error: ReferenceError: regeneratorRuntime is not defined
This is my gulp file in the test folder:
var gulp = require('gulp')
var gutil = require('gulp-util')
var gulpLoadPlugins = require('gulp-load-plugins')
var plugins = gulpLoadPlugins()
var babel = require('gulp-babel')
require('babel-register')({
presets:["es2015", "react", "stage-1"]
});
// This is a cheap way of getting 'test:browser' to run fully before 'test:api' kicks in.
gulp.task('test', ['test:browser'], function(){
return gulp.start('test:api')
});
gulp.task('test:api', function () {
global.env = 'test'
gulp.src(['test/unit-tests/server/**/*.spec.js'], {read: false})
.pipe(plugins.mocha({reporter: 'spec'}))
.once('error', function (error) {
console.log(error)
process.exit(1);
})
.once('end', function () {
process.exit(0);
})
});
gulp.task('default', ['test']);
Any help on why this is happening wouldd be much appreciated.
Node version 8 already has support for async/await so you do not need Babel to transform it; indeed, your root .babelrc includes this preset to exclude the regenerator that would transform async/await (and introduce a dependency on regeneratorRuntime):
["env", {"exclude": ["transform-regenerator"]}]
However, in your test file, the configuration does not specify this preset. Instead, it specifies the preset "es2015", which does include the unwanted transform-regenerator (as you can see at https://babeljs.io/docs/plugins/preset-es2015/). If you change this to match the presets in the root .babelrc, you'll get more consistent results.
Strangely i ran into this issue after i upgraded to Node v8.10.0 from v8.6.x . I had used babel-require like so in my test-setup.js
require('babel-register')();
and the testing tools are Mocha,chai,enzyme + JSDOM . I was getting the same issue when i was making a async call to a API, also while using generator functions via sagas. Adding babel-polyfill seemed to have solved the issue.
require('babel-register')();
require('babel-polyfill');
i guess even babel docs themselves advocate using polyfill for generators and such
Polyfill not included
You must include a polyfill separately when using features that require it, like generators.
Ran into the same issue when running mocha tests from within Visual Studio Code.
The solution was to add the necessary babel plugins in the Visual Studio Code settings.json :
"mocha.requires": [
"babel-register",
"babel-polyfill"
],
I've run into this error before myself when using async/await, mocha, nyc, and when attempting to run coverage. There's never an issue when leveraging mocha for running tests, just with mocha tests while leveraging nyc for running coverage.
11) Filesystem:removeDirectory
Filesystem.removeDirectory()
Should delete the directory "./tmp".:
ReferenceError: regeneratorRuntime is not defined
at Context.<anonymous> (build/tests/filesystem.js:153:67)
at processImmediate (internal/timers.js:461:21)
You can fix the issue a couple of different ways.
Method 1 - NPM's package.json:
...
"nyc": {
"require": [
"#babel/register",
"#babel/polyfill"
],
...
},
...
It really depends which polyfill package you're using. It's recommended to use the scoped (#babel) variant: #babel/pollyfill. However, if you're using babel-polyfill then ensure that's what you reference.
Method 2 - Direct Import
your-test-file.js (es6/7):
...
import '#babel/polyfill';
...
OR
your-test-file.js (CommonJS):
...
require("#babel/polyfill");
...
Don't assign it to a variable, just import or require the package. Again, using the package name for the variant you've sourced. It includes the polyfill and resolves the error.
HTH

Webpack fails with Node FFI and Typescript - dynamic require error

In a simple Typescript program I require Node FFI with
import * as Electron from 'electron';`
import * as ffi from 'ffi';`
and then
mylib = ffi.Library('libmoi', {
'worker': [ 'string', [ 'string' ] ],
'test' : [ 'string', [] ]
} );
Linking that up via webpack yields
WARNING in ./~/bindings/bindings.js
Critical dependencies:
76:22-40 the request of a dependency is an expression
76:43-53 the request of a dependency is an expression
# ./~/bindings/bindings.js 76:22-40 76:43-53
The problem seems to be that FFI has a dynamic require and the fix seems to be to apply webpack.ContextReplacementPlugin in the webpack.config.js file.
This is a bit out of my reach, but an example for an Angular case is:
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
root('./src') // location of your src
)
]
Any idea how to do this for FFI?
Here is the answer: github issue comment on the Johnny-Five repo
Quoting from brodo's answer, this is what you do to stop webpack getting snarled up with "bindings" and similar:
... the webpack config looks like this:
module.exports = {
plugins: [
new webpack.ContextReplacementPlugin(/bindings$/, /^$/)
],
externals: ["bindings"]
}
I also had a similar issue, somehow, I managed to resolve it. I will first explain my understanding.
Main work of webpack is to bundle the separate code file into one file, by default it bundles all the code that is referenced in its tree.
Generally two types of node_modules:
To be used on browser side(angular, rxjs etc)
To be used on nodejs side(express, ffi etc)
It is safer to bundle browser side node_module but not safer to bundle node side node_module because they are not designed like that So the solution is below two steps:
Give appropriate target(node, electron etc) in webpack.config.js file e.g "target":'electron-renderer' by default it is browser
Declare node_side module as external dependency in your webpack.config.js file e.g.
"externals": {
"bindings": "require('bindings')",
"ffi": "require('ffi')"
}

Webpack: expressing module dependency

I'm trying to require the bootstrap-webpack module in my webpacked application.
It appears to need jQuery, since the bundled javascript then throws the following:
Uncaught ReferenceError: jQuery is not defined
How do I go about specifying to webpack that jQuery is a dependency for the bootstrap-webpack module, to fix this issue? It feels like it should be trivial, but I've been struggling to figure it out.
I've tried adding:
"jquery": "latest"
to the dependecies in the bootstrap-webpack's package.json, but this didn't work. The documentation is incomplete, and I can't seem to find much about this issue. It should be trivial, right? Help!
There are two possible solutions:
Use the ProvidePlugin: It scans the source code for the given identifier and replaces it with a reference to the given module, just like it has been required.
// webpack.config.js
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
};
Use the imports-loader: It provides the possibility to prepend preparations like require() statements.
// webpack.config.js
{
...
module: {
loaders: [
{ test: require.resolve("jquery"), loader: "imports?jQuery=jquery" }
]
}
}
In that case you need to run npm install imports-loader --save before.
Via this github issue.
Install expose-loader and add require('expose?$!expose?jQuery!jquery'); to your main entry point just before you require webpack-bootstrap.
This will set jQuery on the window so any file can get at it. Be careful with this method all files will then have access to that version of jQuery regardless of whether it was explicitly required.

StealJS and CanJS

I'm having problems using canJS together with stealjs, i've cloned the repo of javascriptmvc (3.3 use canJS). Now i've this folder structure
/js
/can
/documentjs
/funcunit
/plugins
.
.
.
In another part of my application i've a "standalone module" e.g layout (generated using the scaffolding tool).
I load this module using "js/steal/steal.js?path/to/module/layout" inside my page and it works. If I stole some jquery plugins (e.g. located in the main js folder) inside my layout.js like so:
steal('plugins/jqueryplugin.js', 'plugins/jqueryplugin.css', function() {
// my code here
});
it still work, but when i try to add in the list of "dependecies" some component from "canJS" (even fixture.js generated with the tool...because it stoles can.fixture) it just stops to work and breaks everything. I've also tried using:
steal('that').then('this', function() {});
But i've the same results.....fail!!! anyone have any hints?
Ok i found the problem. There is nothing wrong with stealjs and canjs, but
canjs just load its own version of jquery
that will break my application. Now I need to find a way to load canjs and jquery separately (i use yii and some extensions need to have jquery loaded at a certain time so cannot wait for canjs).
Is the issue the version of jQuery or the order of dependencies?
You can configure steal via the stealconfig.js to use another version of jQuery and manage any dependencies.
An example can be found in the github repo: (this example does not show dependencies so i added one below)
https://github.com/bitovi/steal/blob/master/stealconfig.js
steal.config({
map: {
"*": {
"jquery/jquery.js": "jquery", // Map to path
"bootstrap/bootstrap.js": "bootstrap",
"can/util/util.js": "can/util/jquery/jquery.js"
}
},
paths: {
"jquery": "can/lib/jquery.1.8.3.js", // Path to jQuery
"bootstrap": "lib/bootstrap.js"
"yui/yui.js" : "can/lib/yui-3.7.3.js",
},
shim : {
jquery: {
exports: "jQuery"
},
bootstrap: { // A dependency example
'deps': ['jquery']
}
},
ext: {
js: "js",
css: "css",
less: "steal/less/less.js",
coffee: "steal/coffee/coffee.js",
ejs: "can/view/ejs/ejs.js",
mustache: "can/view/mustache/mustache.js"
}
});
Note: this is an untested example, hope this helps.
i had problem too with stealJs i have known that it work well with JavascriptMVC,
now i'm using AMD requireJs to dependency manage, an it works great with canjs.
here is the documentation http://canjs.com/guides/using-require.html, i hope that it help you!

Resources