"it()" seems to get stuck in jasmine test - jasmine

I am using karma & jasmine to do unit tests, and I am trying to do my first test. I am using the first example here:
https://jasmine.github.io/1.3/introduction.html#section-Matchers
and it didn't seem to do anything, so I added some logging and tried to make it catch an error:
console.log('a');
describe("A suite", function() {
console.log('b', typeof(it));
it("contains spec with an expectation", function() {
console.log('c');
expect(true).toBe(false);
});
});
And this is what my output comes out with:
Chrome 43.0.2357 (Mac OS X 10.10.3) LOG: 'a'
Chrome 43.0.2357 (Mac OS X 10.10.3) LOG: 'b', 'function'
so it looks like nothing internal to the "it" function gets executed since 'c' is never outputted. Am I missing something?
Update
So this is the grunt task I am running:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
karma: {
unit: {
configFile: 'karma.conf.js'
}
}
});
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['karma']);
};
And this is my package.json with the list of installed npm packages:
{
"name": "abc.com",
"version": "0.0.1",
"private": true,
"dependencies": {
"bcrypt": "^0.8.3",
"body-parser": "^1.0.2",
"bower": "^1.4.1",
"ejs": "^2.3.1",
"email-templates": "^2.0.0-beta.1",
"error-handler": "^0.1.4",
"errorhandler": "^1.3.6",
"express": "~4.1.1",
"express-session": "^1.11.2",
"grunt": "^0.4.5",
"jade": "~0.31.2",
"jasmine": "^2.3.1",
"jasmine-runner": "^0.2.9",
"karma": "^0.12.37",
"karma-chrome-launcher": "^0.2.0",
"karma-jasmine": "^0.3.5",
"karma-junit-reporter": "^0.2.2",
"method-override": "^1.0.0",
"morgan": "^1.0.0",
"mysql": "^2.6.2",
"nodemailer": "^1.3.4",
"protractor": "^1.1.1",
"shelljs": "^0.2.6",
"xoauth2": "^1.0.0"
},
"scripts": {
"prestart": "npm install",
"postinstall": "bower install --allow-root",
"start": "supervisor -n error app.js",
"pretest": "npm install",
"test": "karma start karma.conf.js",
"test-single-run": "karma start karma.conf.js --single-run",
"preupdate-webdriver": "npm install",
"update-webdriver": "webdriver-manager update",
"preprotractor": "npm run update-webdriver",
"protractor": "protractor e2e-tests/protractor.conf.js",
"update-index-async": "node -e \"require('shelljs/global'); sed('-i', /\\/\\/##NG_LOADER_START##[\\s\\S]*\\/\\/##NG_LOADER_END##/, '//##NG_LOADER_START##\\n' + sed(/sourceMappingURL=angular-loader.min.js.map/,'sourceMappingURL=bower_components/angular-loader/angular-loader.min.js.map','app/bower_components/angular-loader/angular-loader.min.js') + '\\n//##NG_LOADER_END##', 'app/index-async.html');\""
},
"configs": {
"client_javascript_paths": [
"public/components/common/helpers.js",
"public/libs/bower_components/html5-boilerplate/js/vendor/modernizr-2.6.2.min.js",
"public/libs/bower_components/jquery/dist/jquery.min.js",
"public/libs/bower_components/angular/angular.js",
"public/libs/bower_components/angular-route/angular-route.js",
"public/libs/bower_components/angular-resource/angular-resource.js",
"public/libs/bower_components/d3/d3.js",
"public/libs/bower_components/c3/c3.js",
"public/libs/bower_components/angular-chart/angular-chart.js",
"public/libs/bower_components/moment/moment.js",
"public/components/common/filters.js",
"public/components/notify/notify.js",
"public/components/static/static.js",
"public/components/account/account.js",
"public/components/auth/auth.js",
"public/components/formatted-table/formatted-table.js",
"public/app.js",
"public/libs/underscore.js"
]
},
"devDependencies": {
"jasmine": "^2.3.1",
"jasmine-core": "^2.3.4",
"karma": "^0.12.37",
"karma-chrome-launcher": "^0.2.0",
"karma-jasmine": "^0.3.5",
"karma-phantomjs-launcher": "^0.2.0",
"phantomjs": "^1.9.17"
}
}
And finally, this is my karma.conf.js
module.exports = function(config) {
var package = require('./package.json')
console.log(package.configs.client_javascript_paths);
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: package.configs.client_javascript_paths.concat([
'public/components/**/*.tests.js'
]),
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
and I just run
grunt
to start it to get the output at the top of this.

It is happening because of requirejs framework you use with karma. If you don't need it, then you could just remove it from karma.conf.js and test will work just fine. But if you actually need it, then I would suggest to look at this documentation page, explaining how to configure requirejs for karma, it actually requires an extra file.
Using the files you've presented in the question I was able to execute the tests after the following steps:
first create a backup of karma.conf.js
use CLI command karma init to reinitiate creation of karma config
on the step Do you want to use Require.js ? selected Yes
on the step Do you wanna generate a bootstrap file for RequireJS? selected Yes
copied everything from a backup and added a file that was generated by karma init, it should be called test-main.js, to the list of watched files:
module.exports = function(config) {
var package = require('./package.json');
config.set({
// ...
files: package.configs.client_javascript_paths.concat([
'public/components/**/*.tests.js',
'test-main.js', // here it is
])
// ...
});
};

Related

React Native Web implement SSR

https://necolas.github.io/react-native-web/docs/rendering/
After reading the SSR example from the document, I still don't know how to implement SSR
And I don't want to apply SSR with other framework like NextJS
Can anyone show me an example or give me some advice
I'm posting this, not as a direct answer to the original question, because it's targeted directly SSR with NextJS, and the OP needed SSR independently from frameworks like NextJS. However, understanding it with NextJS can get anyone closer with things, because they key relies in Webpack config that NextJS also use as SSR in its encapsulation config.
First thing to know is that, once a Package has been written for React Native, it need to be transpiled first to be able to be used in Web, with webpack config.externals.
let modulesToTranspile = [
'react-native',
'react-native-dotenv',
'react-native-linear-gradient',
'react-native-media-query',
'react-native-paper',
'react-native-view-more-text',
// 'react-native-vector-icons',
];
Then you need to alias some react-native packages to react-native-web equivalent to let package use web version of modules like:
config.resolve.alias = {
...(config.resolve.alias || {}),
// Transform all direct `react-native` imports to `react-native-web`
'react-native$': 'react-native-web',
'react-native-linear-gradient': 'react-native-web-linear-gradient',
};
At this point, you almost get the essential. The rest is normal Webpack config for the normal Application. Also, it needs some additional config in native config file too. I will post all configs content.
For NextJS: next.config.js :
const path = require('path');
let modulesToTranspile = [
'react-native',
'react-native-dotenv',
'react-native-linear-gradient',
'react-native-media-query',
'react-native-paper',
'react-native-view-more-text',
// 'react-native-vector-icons',
];
// console.log('modules to transpile', modulesToTranspile);
// import ntm = from 'next-transpile-modules';
// const withTM = ntm(modulesToTranspile);
// logic below for externals has been extracted from 'next-transpile-modules'
// we won't use this modules as they don't allow package without 'main' field...
// https://github.com/martpie/next-transpile-modules/issues/170
const getPackageRootDirectory = m =>
path.resolve(path.join(__dirname, 'node_modules', m));
const modulesPaths = modulesToTranspile.map(getPackageRootDirectory);
const hasInclude = (context, request) => {
return modulesPaths.some(mod => {
// If we the code requires/import an absolute path
if (!request.startsWith('.')) {
try {
const moduleDirectory = getPackageRootDirectory(request);
if (!moduleDirectory) {
return false;
}
return moduleDirectory.includes(mod);
} catch (err) {
return false;
}
}
// Otherwise, for relative imports
return path.resolve(context, request).includes(mod);
});
};
const configuration = {
node: {
global: true,
},
env: {
ENV: process.env.NODE_ENV,
},
// optimizeFonts: false,
// target: 'serverless',
// bs-platform
// pageExtensions: ['jsx', 'js', 'bs.js'],
// options: { buildId, dev, isServer, defaultLoaders, webpack }
webpack: (config, options) => {
// config.experimental.forceSwcTransforms = true;
// console.log('fallback', config.resolve.fallback);
if (!options.isServer) {
// We shim fs for things like the blog slugs component
// where we need fs access in the server-side part
config.resolve.fallback.fs = false;
} else {
// SSR
// provide plugin
config.plugins.push(
new options.webpack.ProvidePlugin({
requestAnimationFrame: path.resolve(__dirname, './polyfills/raf.js'),
}),
);
}
// react-native-web
config.resolve.alias = {
...(config.resolve.alias || {}),
// Transform all direct `react-native` imports to `react-native-web`
'react-native$': 'react-native-web',
'react-native-linear-gradient': 'react-native-web-linear-gradient',
};
config.resolve.extensions = [
'.web.js',
'.web.ts',
'.web.tsx',
...config.resolve.extensions,
];
config.externals = config.externals.map(external => {
if (typeof external !== 'function') {
return external;
}
return async ({ context, request, getResolve }) => {
if (hasInclude(context, request)) {
return;
}
return external({ context, request, getResolve });
};
});
const babelLoaderConfiguration = {
test: /\.jsx?$/,
use: options.defaultLoaders.babel,
include: modulesPaths,
// exclude: /node_modules[/\\](?!react-native-vector-icons)/,
};
babelLoaderConfiguration.use.options = {
...babelLoaderConfiguration.use.options,
cacheDirectory: false,
// For Next JS transpile
presets: ['next/babel'],
plugins: [
['react-native-web', { commonjs: true }],
['#babel/plugin-proposal-class-properties'],
// ['#babel/plugin-proposal-object-rest-spread'],
],
};
config.module.rules.push(babelLoaderConfiguration);
return config;
},
};
// module.exports = withTM(config);
module.exports = configuration;
SSR will fail to build when missing some functions at server side. The most popular with React Native is requestAnimationFrame. I added it add a Webpack Plugin to mimic it. It can be an empty function or Polyfill:
The file 'polyfills/raf.js(I just put it assetImmediate`):
const polys = { requestAnimationFrame: setImmediate };
module.exports = polys.requestAnimationFrame;
The Babel config is necessary for the last part of it, couldn't work directly in next config. babel.config.js :
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [['module:react-native-dotenv'], 'react-native-reanimated/plugin'],
};
And finally, my list of packages in package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"android": "react-native run-android",
"android:dev": "adb reverse tcp:8081 tcp:8081 && react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint .",
"web": "webpack serve -d source-map --mode development --config \"./web/webpack.config.js\" --inline --color --hot",
"build:web": "webpack --mode production --config \"./web/webpack.config.js\" --hot",
"next:dev": "next",
"next:build": "next build",
"next:start": "next start",
"next:analyze": "ANALYZE=true next build"
},
"dependencies": {
"#material-ui/core": "^4.12.4",
"#react-native-async-storage/async-storage": "^1.17.3",
"#react-navigation/drawer": "^6.4.1",
"#react-navigation/native": "^6.0.10",
"#react-navigation/stack": "^6.2.1",
"#reduxjs/toolkit": "^1.8.1",
"axios": "^0.21.1",
"local-storage": "^2.0.0",
"lottie-ios": "^3.2.3",
"lottie-react-native": "^5.1.3",
"lottie-web": "^5.9.4",
"moment": "^2.29.1",
"next": "^12.1.6",
"nookies": "^2.5.2",
"numeral": "^2.0.6",
"raf": "^3.4.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-native": "0.68.1",
"react-native-dotenv": "^2.5.5",
"react-native-gesture-handler": "^2.4.2",
"react-native-keyboard-aware-scroll-view": "^0.9.5",
"react-native-linear-gradient": "^2.5.6",
"react-native-media-query": "^1.0.9",
"react-native-paper": "^4.12.1",
"react-native-progress": "^5.0.0",
"react-native-read-more-text": "^1.1.2",
"react-native-reanimated": "^2.8.0",
"react-native-safe-area-context": "^4.2.5",
"react-native-screens": "^3.13.1",
"react-native-share-menu": "^6.0.0",
"react-native-svg": "^12.3.0",
"react-native-svg-transformer": "^1.0.0",
"react-native-vector-icons": "^9.1.0",
"react-native-view-more-text": "^2.1.0",
"react-native-web": "^0.17.7",
"react-native-web-linear-gradient": "^1.1.2",
"react-redux": "^8.0.1"
},
"devDependencies": {
"#babel/plugin-proposal-class-properties": "^7.14.5",
"#next/bundle-analyzer": "^12.2.2",
"#react-native-community/eslint-config": "^2.0.0",
"#swc/cli": "^0.1.57",
"#swc/core": "^1.2.179",
"eslint": "^7.28.0",
"metro-react-native-babel-preset": "^0.66.0",
"url-loader": "^4.1.1",
"webpack": "^5.39.1",
"webpack-cli": "^4.7.2"
},
"jest": {
"preset": "react-native-web"
},
"sideEffects": false
}
NB: only React-Native packages used also in Web has to be transpiled. Some React-Native packages can be used ONLY in Native, so transpiling them for Web will add up unnecessary chunks of heavy codes in the Web, which is not good. React-Native-Web/React-Native is already more heavy for Web than normal packages made directly for Web.
TIPS to keep it cool with NextJS
Avoid writing conditional Platform.OS === 'web' on small components where you plan to use either a React-Native module or a Web module, which can cause all of them to load unnecessary Native-Only package on web codes. If size is not important, then you can ignore it. Add extension .web.js and .native.js at the end and separate the small codes. For example I write separate Functions and Components for : Storage.web.js, Storage.native.js, CustomLink.web.js, CustomLink.native.js, and hooks useCustomNavigation.web.js, useCustomNavigation.native.js, so that I call CustomLink in place of NextJS Link/router and React-Navigation Link/navigation.
I use react-native-media-query package as life saver for advanced media queries for all SSR/CSR Web and Native responsive display. The App can be restructured on big screen like normal Desktop Web, and be shrunk to Mobile View on the go, EXACTLY LIKE Material-UI on NextJS.

using ES2015 with mocha, karma and headless chrome for testing

I have a problem with setting up a test environment for a single page application. I am able to run my tests with headless chrome via karma and mocha but I can´t write tests with ES6 Syntax.
My current start command is
karma start --browsers ChromeHeadless karma.config.js --single-run
my karma.config.js
module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai'],
files: ['test/**/*spec.js'],
reporters: ['nyan'],
port: 9876, // karma web server port
colors: true,
logLevel: config.LOG_INFO,
browsers: ['ChromeHeadless'],
autoWatch: true,
singleRun: false, // Karma captures browsers, runs the tests and exits
concurrency: Infinity,
})
}
I am able to write normal tests but cant use ES6 Syntax here. When I try to import some react components I get this error:
HeadlessChrome 0.0.0 (Linux 0.0.0)
Uncaught SyntaxError: Unexpected token import
at http://localhost:9876/base/test/components.spec.js?b89d2ba6de494310860a60ad2e9e25aea5eb3657:2
So I have to setup babel somehow to compile my test files first. When I try to use compilers: ['js:babel-core/register'] in my karma config its not gonna work.
I also have seen that compilers seems to be deprecated soon so I also tried require: ['babel-core/register'] but it still won´t compile to use ES6 for my test files.
Any idea how to configurate my karma file to write my tests with ES6 ?
Just in case its important. This is my webpack.config.js
const path = require('path');
const ServiceWorkerWebpackPlugin = require('serviceworker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: 'index_bundle.js'
},
module: {
loaders: [
{test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/},
{test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/}
]
},
plugins: [
new ServiceWorkerWebpackPlugin({
entry: path.join(__dirname, 'src/sw.js'),
}),
HtmlWebpackPluginConfig
],
devServer: {
hot: false,
inline: false,
historyApiFallback: true
}
};
To make things more clear here is a sample project (it's fully runnable, you can fill out files and play around). Just two things to mention: I used jamsine instead of mocha and real 'Chrome' browser instead of headless. Runnable via npm run test command.
files structure
/
karma.conf.js
package.json
sample.js
sampleTest.js
webpack.test.config.js
karma.conf.js:
// Karma configuration
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: ['*Test.js'],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
preprocessors: {
'*Test.js': [ 'webpack'] //preprocess with webpack
},
// test results reporter to use
reporters: ['progress'],
// setting up webpack configuration
webpack: require('./webpack.test.config'),
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
browsers: ['Chrome'],
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level how many browser should be started simultaneous
concurrency: Infinity
})
}
package.json (only relevant stuff):
{
"scripts": {
"test": "node_modules/karma/bin/karma start karma.conf.js"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"jasmine-core": "^2.8.0",
"karma": "^2.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-jasmine": "^1.1.1",
"karma-webpack": "^2.0.9",
"webpack": "^3.10.0"
}
}
sample.js:
export default function(data){
return data;
}
sampleTest.js:
import sample from 'sample';
describe('Sample', function(){
it('is defined', function(){
expect(sample).toBeDefined();
});
it('returns argument', function(){
expect(sample(0)).toBe(0);
})
});
webpack.test.config.js:
module.exports = {
module: {
rules: [
{
test: /tests\/.*\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
}
]
},
resolve: {
modules: ["node_modules", './'],
extensions: [".js"]
}
};
Karma's webpack plugin is used to inform karma that it should prepare files using webpack and specific webpack configuration before sending them to the browser.
Please note key points:
test files pattern in karma.conf.js
pattern to preprocess files (should match the pattern above)
webpack entry in karma.conf.js file
module entry in webpack.test.config.js
p.s. personally I don't use separate patterns for files, I use a separate file (named, say, tests.webpack.js) to have a single place where the way to find test files is defined:
//make sure you have your directory and regex test set correctly
var context = require.context('.', true, /.*Test\.js$/i);
context.keys().forEach(context);
and have in karma.conf.js (paths are irrelevant to sample project above):
files: [
'tests/tests.webpack.js',
],
preprocessors: {
'./tests/tests.webpack.js': [ 'webpack'] //preprocess with webpack
}
You need to convert ESModule in commonjs module with the babel-plugin-transform-es2015-modules-commonjs plugin
In your .babelrc file :
{
"plugins": [
"transform-es2015-modules-commonjs"
]
}
Update :
You can set the plugin in your webpack configuration :
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-transform-es2015-modules-commonjs')]
}
}

SASS not compiling in Phoenix app

I'm just getting started with Phoenix and Elixir, and am coming to a hurdle at the very start with my scss/css files.
Following some blogs/articles, I have done the following so far:
renamed app.css to app.scss
Created new dir '_scss' where I am putthing my scss files.
In app.scss I am importing my scss files.
#import "../_scss/_foundation.scss";
package.json looks like:
{
"repository": {},
"license": "MIT",
"scripts": {
"deploy": "brunch build --production",
"watch": "brunch watch --stdin"
},
"dependencies": {
"babel-preset-es2015": "^6.24.1",
"bourbon": "^4.3.4",
"bourbon-neat": "^2.0.0",
"foundation-sites": "^6.3.1",
"phoenix": "file:deps/phoenix",
"phoenix_html": "file:deps/phoenix_html",
"purecss": "^0.6.2",
"sass-brunch": "^2.10.4"
},
"devDependencies": {
"babel-brunch": "~6.0.0",
"brunch": "2.7.4",
"clean-css-brunch": "~2.0.0",
"css-brunch": "~2.0.0",
"javascript-brunch": "~2.0.0",
"uglify-js-brunch": "~2.0.1"
}
}
And in brunch.config.js I have:
stylesheets: {
joinTo: "css/app.scss",
order: {
after: ["web/static/css/app.scss"] // concat app.css last
}
},
I changed the above to reflect the name change of app.scss. Was that correct?
And when I load the server, the page loads, but without any styling. My terminal just seems to be constantly compiling...
24 Apr 15:01:56 - info: compiling..
What am I doing wrong here?
UPDATE
Seems to be the individual file. Int his case foundation.scss. I just tried another framework , Bulma, and it worked instantly.

Using Slick-Carousel and NPM

Still trying to master NPM and hit some roadblocks.
My slick-carousel works great when I use the CDN process. But I'm doing everything in NPM so figured I should do the same with this plug-in, but can't seem to get it off the ground.
Ran the install:
npm install slick-carousel --save
Which adds to my package.json file:
"devDependencies": {
"copy-webpack-plugin": "^3.0.1",
"css-loader": "^0.23.1",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
"gh-pages": "^0.11.0",
"html-webpack-plugin": "^2.21.0",
"img-loader": "^1.3.1",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack": "^1.13.1"
},
"dependencies": {
"font-awesome-webpack": "0.0.4",
"jquery": "^3.0.0",
"slick-carousel": "^1.6.0"
}
I'm smart enough to know that I need to require the file in my index.js file:
var $ = require('jquery');
require("../css/style.css");
require("font-awesome-webpack");
require("slick-carousel");
I can see that I now have all the jQuery for slick-carousel, but none of the css.
Now I figure I should require the two .css files living in the node_modules folder:
require("slick-carousel/slick/slick.css");
require("slick-carousel/slick/slick-theme.css");
And this is where it all breaks. The slick.css file loads and the basic slick-carousel is now working in my html output. But the slick-theme file breaks everything by pushing this error:
./~/slick-carousel/slick/ajax-loader.gif
Module parse failed: /Users/ryanbuchholtz/Documents/thinkful/haventower/node_modules/slick-carousel/slick/ajax-loader.gif Unexpected character '' (1:7)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '' (1:7)
This makes me think something is broken in my webpack.config.js:
var path = require('path');
var packageData = require('./package.json');
var filename = [packageData.name, packageData.version, 'js'];
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var CopyWebpackPlugin = require('copy-webpack-plugin');
var plugins = [
new HtmlWebpackPlugin({
inject: 'head',
template: 'index.html',
minify: {
"collapseWhitespace": true,
"removeComments": true,
"removeRedundantAttributes": true,
"removeScriptTypeAttributes": true,
"removeStyleLinkTypeAttributes": true
}
}),
new ExtractTextPlugin('style.css')
];
module.exports = {
entry: {
main: [
path.resolve(__dirname, packageData.main)
]
},
output: {
path: path.resolve(__dirname, 'build'),
filename: filename.join('.'),
},
devtool: 'source-map',
plugins: plugins,
module: {
loaders: [
{
test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader", "file-loader")
},
{ test: /\.(jpe?g|png|gif|svg)$/, loader: "file-loader"
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff"
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader"
}
]
}
};
I could really use some assistance in the best way to use slick-carousel while building in NPM and with webpack. So many moving pieces and, when I kinda think I get it, this comes along and I spend 7 hours trying to fix it before asking for help.
Any help is deeply appreciated.
I had the same issue, but I didn't want to change slick-carousel in my project, so one month late but here is how I solved it:
First install Webpack image-loader:
$ npm install image-webpack-loader --save-dev
Then change these lines (in your webpack configuration):
loaders: [{
test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader", "file-loader")
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader"
}]
This will change file-loader (what you are using for loading images) for image-loader, it will know how to compile .gif files and other formats.
For aditional information about this, you can check the github page
Also, if you are using ReactJS, don't use slick-carousel directly, because it uses direct DOM manipulation thanks to JQuery dependency, right now I'm using react-slick is very stable and has cool options like settings based on responsive layout custom prev and next arrows and more.
I hope it help you
require("slick-carousel/slick/slick.css");
require("slick-carousel/slick/slick-theme.css");
From what I understand you do not need both of these - only one.
Slick-theme is the default CSS, while Slick you integrate.
I could be wrong (I'm really new to development) but I've had no problems with the initial configuration!

Grunt fails trying to load an empty module

I'm a bit stuck with my Jenkins setup on OSX Lion 10.7.3.
I'm using Grunt in my webapp to run Jasmine tests, build less, create cache manifest etc. Everything works on my laptop Lion 10.7.5, but on the server box grunt fails from time to time with the following error:
$ grunt less
module.js:340
throw err;
^
Error: Cannot find module ''
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at ChildProcess.<anonymous> (/usr/local/lib/node_modules/grunt-cli/bin/grunt:44:3)
at ChildProcess.EventEmitter.emit (events.js:99:17)
at Process._handle.onexit (child_process.js:678:10)
This is intermittent, it fails approximately once out of five runs and is not task specific. It fails with the same rate when running grunt manifest or grunt test.
Once thing I noticed is that when it works it takes a second or two until the task starts executing, but when it fails it fails immediately.
I tried to remove node_modules, npm cache clear, reinstalling grunt-cli. Nothing works.
Here's my package.json:
{
"name": "webapp",
"version": "0.0.0",
"dependencies": {},
"devDependencies": {
"grunt": "0.4.0rc7",
"grunt-contrib-copy": "0.4.0rc7",
"grunt-contrib-concat": "0.1.2rc6",
"grunt-contrib-coffee": "0.4.0rc7",
"grunt-contrib-uglify": "0.1.1rc6",
"grunt-contrib-compass": "0.1.1rc8",
"grunt-contrib-jshint": "0.1.1rc6",
"grunt-contrib-mincss": "0.4.0rc7",
"grunt-contrib-connect": "0.1.1rc6",
"grunt-contrib-clean": "0.4.0rc6",
"grunt-contrib-htmlmin": "0.1.1rc7",
"grunt-contrib-imagemin": "0.1.1rc8",
"grunt-contrib-livereload": "0.1.0rc8",
"grunt-contrib-jasmine": "~0.3.2",
"grunt-contrib-less": "0.5.0",
"grunt-manifest": "0.4.0",
"grunt-jslint": "0.2.5",
"grunt-bower-hooks": "~0.2.0",
"grunt-usemin": "~0.1.7",
"grunt-regarde": "~0.1.1",
"grunt-requirejs": "~0.3.1",
"grunt-mocha": "~0.2.2",
"grunt-open": "~0.1.0",
"matchdep": "~0.1.1"
},
"engines": {
"node": ">=0.8.0"
}
}
npm and node versions:
$ npm -version
1.2.11
$ node --version
v0.8.20
I have now stripped down both packages.json and Gruntile.js:
$ cat package.json
{
"name": "webapp",
"version": "0.0.0",
"dependencies": {},
"devDependencies": {
"grunt": "0.4.0rc7",
"grunt-manifest": "0.4.0",
"matchdep": "~0.1.1"
},
"engines": {
"node": ">=0.8.0"
}
}
$ cat Gruntfile.js
'use strict';
module.exports = function (grunt) {
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
manifest: {
generate: {
options: {
basePath: 'app/',
exclude: ['js/lib/amp/com.vaultus.api.WebApiAggregated.cache.js', 'js/lib/amp/com.vaultus.api.DebugWebApiAggregated.cache.js'],
timestamp: true
},
src: [
'index-hybrid.html',
'*.xml',
'js/**/*.js',
'css/**/*.css',
'css/images/**/*',
'i18n/**/*.js',
'template/**/*.html'
],
dest: 'app/cache-manifest.mf'
}
}
});
grunt.registerTask('build', [
'manifest'
]);
grunt.registerTask('default', ['build']);
};
No luck :(
We were hitting this issue on our CI builds.
After a bit of digging it looks like this was a bug in grunt-cli 0.1.6 and has been fixed in 0.1.7 of grunt-cli.

Resources