Ive been banging my head against the wall for hours on this and Im just stumped. Any help is greatly appreciated!
Basically, super basic repo setup to get Browserify working with Backbone and Marionette. Just isnt happening.
app.js:
var View = require('./view'),
$ = require('jquery'),
Backbone = require('backbone'),
Marionette = require('backbone.marionette');
Backbone.$ = window.$;
var myview = new View();
myview.render();
$('body').css('background-color','#f0f0f0');
var mapp = new Marionette.Application();
console.dir(Marionette);
Simple. My view is event simpler:
var Backbone = require('backbone');
module.exports = TestView = Backbone.View.extend({
render: function() {
$('body').append('<p>Hello world! (Backbone view rendered successfully!</p>');
}
});
And finally my package.json snippet specific to browserify:
"browser": {
"jquery": "./requires/jquery.js",
"underscore": "./requires/underscore.js",
"backbone": "./requires/backbone.js",
"backbone.wreqr": "./requires/backbone.wreqr.js",
"backbone.babysitter": "./requires/backbone.babysitter.js",
"backbone.marionette": "./requires/backbone.marionette.js"
},
"browserify-shim": {
"jquery": "$",
"underscore": "_",
"backbone": {
"exports": "Backbone",
"depends": [
"underscore:underscore"
]
},
"backbone.babysitter": {
"exports": "Backbone.BabySitter",
"depends": [
"backbone:Backbone"
]
},
"backbone.wreqr": {
"exports": "Backbone.Wreqr",
"depends": [
"backbone:Backbone"
]
},
"backbone.marionette": {
"exports": "Marionette",
"depends": [
"jquery:jQuery",
"backbone:Backbone",
"underscore:_"
]
}
},
"browserify": {
"transform": [
"browserify-shim"
]
}
I feel like Im 99% there! The final issue is that jquery doesnt appear to be loading as a dependency for Marionette. The console.log thats in app.js shows that $ for the Marionette object is undefined. The error that shows in the console log when you run the app is:
this._deferred = Marionette.$.Deferred();
Uncaught TypeError: Cannot call method 'Deferred' of undefined
At this point its something stupid Im doing and I just cant put my finger on it. If its any easier, you can check out the repo of a super basic project I creates solely to figure this out.
https://github.com/jkat98/browserifytest
Thanks!!!!!!
Take a look at the browserify example we have done for people looking to use the stack you are asking about.
https://github.com/marionettejs/marionette-integrations/tree/master/browserify
(Full disclosure: I haven't used Browserify, but it seems very similar to ReuqireJS, so I'm basing my answer on that...)
Backbone requires jQuery, but you're not depending on it in your shim config. Try with:
"backbone": {
"exports": "Backbone",
"depends": [
"jquery:jQuery",
"underscore:underscore"
]
},
Then, you can also simply your Marionette config:
"backbone.marionette": {
"exports": "Marionette",
"depends": [
"backbone:Backbone"
]
}
You don't need the AMD versions of Marionette, etc. Just be aware that the non-AMD versions will register global variables (e.g. $).
In addition, you might be interested in the free sample chapter to my Marionette and RequireJS book to get you started.
We use marionette with browerify, but do it with cartero via the browserify option.
So I pretty much muscled through this and got it working. For anyone interested or in the future:
I decided to take the shim details out of package.json and put them in a separate config/shim.js file.
I also fixed the logic in the shim a bit to get it to actually work correctly. That was pretty much my problem, improperly defining dependencies. I also think I needed to separately define Wreqr and BabySitter as they are dependencies of Marionette.
updated package.json file:
"browser": {
"jquery": "./client/requires/jquery/js/jquery.js",
"underscore": "./client/requires/underscore/js/underscore.js",
"backbone": "./client/requires/backbone/js/backbone.js",
"backbone.wreqr": "./client/requires/backbone.wreqr/js/backbone.wreqr.js",
"backbone.babysitter": "./client/requires/backbone.babysitter/js/backbone.babysitter.js",
"backbone.marionette": "./client/requires/backbone.marionette/js/backbone.marionette.js"
},
"browserify-shim": "./config/shim.js",
"browserify": {
"transform": [
"browserify-shim",
"hbsfy"
]
}
.config/shim.js file:
module.exports = {
"jquery": "$",
"underscore": "_",
"backbone": {
"exports": "Backbone",
"depends": {
"jquery":"$",
"underscore":"underscore"
}
},
"backbone.babysitter": {
"exports": "Backbone.BabySitter",
"depends": {
"backbone":"Backbone"
}
},
"backbone.wreqr": {
"exports": "Backbone.Wreqr",
"depends": {
"backbone":"Backbone",
"underscore":"_"
}
},
"backbone.marionette": {
"exports": "Marionette",
"depends": {
"backbone":"Backbone",
"backbone.wreqr":"Backbone.Wreqr",
"backbone.babysitter":"Backbone.BabySitter"
}
}
};
You don't need to specify it inside of a shim the problem is that the Marionette module doesn't have jQuery attached to it. In this example
var $ = require('jquery'),
Backbone = require('backbone'),
Marionette = require('backbone.marionette')
Backbone.$ = window.$;
var View = require('./view');
var myview = new View();
myview.render();
$('body').css('background-color','#f0f0f0');
var mapp = new Marionette.Application();
console.dir(Marionette);
It should be like this, also use this as an example https://github.com/thejameskyle/marionette-wires/blob/master/src/plugins.js
$ = require('jquery');
Backbone = require('backbone'),
Backbone.$ = $
Marionette = require('backbone.marionette');
var myView = new View();
myView.render();
$('body').css('background-color','#f0f0f0');
var myApp = new Marionette.Application();
console.dir(Marionette);
and then
this._deferred = Backbone.$.Deferred;
I also spent a lot of time searching for solutions, but it was much easier
package.json
...
"dependencies": {
"backbone": "^1.1.2",
"handlebars": "^2.0.0",
"jquery": "^2.1.1",
"lodash": "^2.4.1",
"backbone.marionette": "^2.2.1"
}
...
gruntfile.js
...
browserify: {
vendor: {
src: 'src/js/vendor.js',
dest: 'dist/js/vendor.js',
options: {
alias: [
'./node_modules/handlebars/runtime.js:handlebars',
'./node_modules/lodash/dist/lodash.underscore.js:underscore',
'jquery:',
'backbone:',
'backbone.marionette:'
]
}
},
application: {
src: 'src/js/application.js',
dest: 'dist/js/application.js',
options: {
browserifyOptions: {
debug: true
},
external: [
'handlebars', 'underscore', 'jquery', 'backbone', 'backbone.marionette'
]
}
}
}
...
src/js/vendor.js
require('backbone').$ = require('jquery');
src/js/application.js
var Marionette = require('backbone.marionette');
Full working example: https://gist.github.com/knpsck/a7c2ead6120c7dca152c
Related
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.
I want to use Next.js with Sass and CSS modules but also want to use Ant Design and wanted to use the Less styles for smaller building size.
I'm able to enable either CSS modules or Less loader but not both at the same time. The examples from Next.js were not helping me complete that problem.
Edit: This answer is definitely outdated for current versions of next.js, check the other answers below.
After multiple hours of research I found now finally the right solution and wanted to share it:
.babelrc (no magic here)
{
"presets": ["next/babel"],
"plugins": [
[
"import",
{
"libraryName": "antd",
"style": true
}
]
]
}
next.config.js:
/* eslint-disable */
const withLess = require('#zeit/next-less');
const withSass = require('#zeit/next-sass');
const lessToJS = require('less-vars-to-js');
const fs = require('fs');
const path = require('path');
// Where your antd-custom.less file lives
const themeVariables = lessToJS(
fs.readFileSync(path.resolve(__dirname, './assets/antd-custom.less'), 'utf8')
);
module.exports = withSass({
cssModules: true,
...withLess({
lessLoaderOptions: {
javascriptEnabled: true,
modifyVars: themeVariables, // make your antd custom effective
importLoaders: 0
},
cssLoaderOptions: {
importLoaders: 3,
localIdentName: '[local]___[hash:base64:5]'
},
webpack: (config, { isServer }) => {
//Make Ant styles work with less
if (isServer) {
const antStyles = /antd\/.*?\/style.*?/;
const origExternals = [...config.externals];
config.externals = [
(context, request, callback) => {
if (request.match(antStyles)) return callback();
if (typeof origExternals[0] === 'function') {
origExternals[0](context, request, callback);
} else {
callback();
}
},
...(typeof origExternals[0] === 'function' ? [] : origExternals)
];
config.module.rules.unshift({
test: antStyles,
use: 'null-loader'
});
}
return config;
}
})
});
The final hint how to write the withSass withLess use and to put the cssModules: true in the outer object came from this comment here.
While I was already trying different combinations derived from the examples before:
next+ant+less
next+sass
For completion here the dependencies in my package.json:
...
"dependencies": {
"#zeit/next-less": "^1.0.1",
"#zeit/next-sass": "^1.0.1",
"antd": "^4.1.3",
"babel-plugin-import": "^1.13.0",
"less": "^3.11.1",
"less-vars-to-js": "^1.3.0",
"next": "^9.3.4",
"node-sass": "^4.13.1",
"null-loader": "^3.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"sass": "^1.26.3"
}
...
I hope this helps other people to find this solution faster. :)
#zeit/next-less is deprecated and disables Next's built in CSS support. It also uses a very old version of less and less-loader.
I created a package that injects Less support to Next.js by duplicating the SASS rules and setting them for Less files and less-loader. It works with webpack5 flag.
https://github.com/elado/next-with-less
https://www.npmjs.com/package/next-with-less
While the above answers may work for versions of NextJS lower than 11, they do not work for 11+. I've found excellent success with the following plugin...
https://github.com/SolidZORO/next-plugin-antd-less
I am using elado's package which is -
https://github.com/elado/next-with-less
you will need less and less-loader as dependencies.
after that create a global.less file on styles folder. so it's like ,root> style > global.less and paste this code
#import '~antd/lib/style/themes/default.less';
#import '~antd/dist/antd.less';
#primary-color: #ff9b18;
#border-radius-base: 20px;
and add below code in your next.config.js file which you will create on your root folder.
// next.config.js
const withLess = require("next-with-less");
module.exports = withLess({
lessLoaderOptions: {
/* ... */
},
});
To add Less to the Next.js is easy way.
Need to add 'next-with-less' library (also install less and less-loader) and 'next-compose-plugin'.
To your next.config.js add:
/** #type {import('next').NextConfig} */
const withPlugins = require('next-compose-plugins');
const withLess = require('next-with-less');
const plugins = [
[
withLess,
{
lessLoaderOptions: {},
},
],
];
module.exports = withPlugins(plugins, {
reactStrictMode: true,
swcMinify: true,
});
In our project, there were old scss and css files. They were not using the Next js guidline for CSS modules. So I had to override webpack.config.js. So that works fine. But when we moved the file to the monorepo shared package, babel was not transpiling them. I used the below things, but those did not work for SCSS modules without a .module extension.
next-transile-module.
experimental: { externalDir: true, } in next Js config with root babel.cofig.json
Finally symlink hack worked for external shared files
Use symlinks for shared folder by updating next.config.js
module.exports = {
//...
resolve: {
symlinks: false,
},
};
For anyone who is still having trouble, you don't need any extra package other than our lovely mini-css-extract-plugin. Here is how you solve the issue.
PS: I also added sass to my webpack config. You can use both less and sass/scss files in your project.
next.config.js:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
webpack(config) {
config.module.rules.push(
{
// this part is for css
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, { loader: 'css-loader' }],
},
{
// this part is for sass
test: /\.module\.(scss|sass)$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader' },
{ loader: 'sass-loader' },
],
},
{
// this part is for less
test: /\.less$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
},
{
loader: 'less-loader',
options: {
sourceMap: true,
lessOptions: {
javascriptEnabled: true,
},
},
},
],
}
);
config.plugins.push(
new MiniCssExtractPlugin({
filename: 'static/css/[name].css',
chunkFilename: 'static/css/[contenthash].css',
})
);
return config;
},
};
package.json:
"dependencies": {
"#next/font": "13.1.1",
"css-loader": "^6.7.3",
"less": "^4.1.3",
"less-loader": "^11.1.0",
"mini-css-extract-plugin": "^2.7.2",
"next": "13.1.1",
"next-transpile-modules": "^10.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"sass": "^1.57.1",
"sass-loader": "^13.2.0",
}
I am trying to run tests written in TypeScript using tape and the karma-typescript loader.
In my project I use webpack with graphql-tag/loader and import the queries directly into my TypeScript files like:
import myQuery from "../query/hello.graphql";
These imports are causing issues when I try and run the tests.
module.exports = function (config) {
config.set({
frameworks: ["tap", "karma-typescript"],
files: [
"src/**/*.ts",
"src/**/*.tsx",
"query/**/*.graphql"
],
preprocessors: {
"src/**/*.ts": ["karma-typescript"],
"src/**/*.tsx": ["karma-typescript"]
},
karmaTypescriptConfig: {
compilerOptions: {
"skipLibCheck": true,
"allowSyntheticDefaultImports": true
},
bundlerOptions: {
transforms: [
require("karma-typescript-es6-transform")()
]
}
},
reporters: ["progress", "karma-typescript"],
browsers: ["Firefox"]
});
};
I guess that I would ideally like to perform a second transform on the .graphql files. Based on the approach used in jest-transform-graphql, I tried adding another transform:
function (context, callback) {
if (/\.graphql$/.test(context.module)) {
context.source = loader.call({ cacheable() { } }, context.source);
return callback(undefined, true);
}
return callback(undefined, false);
}
But I still get errors like:
{
"message": "SyntaxError: unexpected token: identifier\nat query/hello.graphql:1:6\n\n",
"str": "SyntaxError: unexpected token: identifier\nat query/hello.graphql:1:6\n\n"
}
How can I apply the transformation to the graphql files, so that I don't get syntax errors from them in the browser?
This might be repeated question for you guys but really I didn't get answer yet.
Here is my multi-capabilities definition in protractor config file.
I want to access the deviceName parameter value. How can I do it?
exports.config = {
directConnect:true,
multiCapabilities: [
{
browserName: 'chrome',
'chromeOptions': {
'mobileEmulation': {
'deviceName': 'iPad'
}
}
}
],
Tried under onPrepare but not giving multi-capabilities values
browser.getCapabilities().then(function(c) {
console.log(c.get('deviceName'));
});
Not sure about solving with getCapabilities(), but you should be able to solve this with getProcessedConfig().
getProcessedConfig will return a promise of your entire configuration settings (and a few protractor defaults). So taking your example:
browser.getProcessedConfig().then((c) => {
console.log(c.capabilities.chromeOptions.mobileEmulation.deviceName);
});
You could make console.log(process.env) in the onPrepare block and find what you want.
Try getProcessedConfig()
http://www.protractortest.org/#/api?view=ProtractorBrowser.prototype.getProcessedConfig
Or just plain old stupid:
let device_name = 'iPad'
exports.config = {
directConnect: true,
multiCapabilities: [{
browserName: 'chrome',
chromeOptions: {
mobileEmulation: {
deviceName: device_name
}
}
}],
onPrepare: function () {
console.log('Device name will be', device_name);
}
Fetching device name worked as advised by Gunderson but now I am running into different issue I am unable to access the variable value outside the code block while in onPrepare.
onPrepare: function () {
browser.getProcessedConfig().then(function (c) {
return global.deviceName
c.capabilities.chromeOptions.mobileEmulation.deviceName;
}).then(function () {
console.log("Device Name is:" + global.deviceName);
customDevice = global.deviceName;
}
);
};
customDevice not printing any value.....which is define as global variable on top of the configuration file.
I know might be doing silly mistake in accessing it...:)
I am trying to set up Browserify with Elixir and Browserify Shim on Laravel 5.2 to use Gulp with my JavaScript files, but I didn't have much luck so far. This should be pretty straightforward to do, but it isn't.
Here is my package.json
{
"private": true,
"devDependencies": {
"gulp": "^3.8.8"
},
"dependencies": {
"bootstrap-sass": "^3.0.0",
"browserify-shim": "^3.8.12",
"jquery": "^2.2.0",
"jquery-ui": "^1.10.5",
"laravel-elixir": "^4.0.0"
},
"browser": {
"app": "./resources/assets/js/app.js",
"utils": "./resources/assets/js/utils.js",
},
"browserify": {
"transform": [
"browserify-shim"
]
},
"browserify-shim": {
"app": {
"depends": [
"jquery:$",
"utils:Utils"
]
},
"utils": {
"depends": [
"jquery:$"
]
},
}
}
gulpfile.js
var elixir = require('laravel-elixir');
elixir(function (mix) {
mix.browserify('main.js', './public/js/bundle.js');
});
Entry script main.js looks like this:
var $ = require('jquery');
var Utils = require('utils');
var App = require('app');
app.js
var App = {
init: function(){
console.log(Utils);
Utils.doSomething();
}
//other methods
};
In short: Utils depends on $, and App depends on both $ and Utils.
When I hit gulp from terminal, bundle.js is correctly created. All scripts are wrapped up in Browserify code (as expected). Each script has all included dependencies, like I configured in package.json so this part looks good as well.
The problem is that all my included dependencies are empty objects. For example, Utils in app.js is empty, and I get an error when I try to call its method "doSomething". Console log prints out an empty object "{}" instead of real object. The only correctly included script is jQuery and it's not an empty object.
What could be wrong here? Do I need to make some changes in my JS files or in configuration to make this work? It looks like I'm pretty close to the solution, but it still does not work and I can't use it at all.
It is the easiest solution to directly use 'exports' from browserify-shim property:
"browserify-shim": {
"app": {
"exports": "App",
"depends": [
"jquery:$",
"utils:Utils"
]
},
"utils": {
"exports": "Utils",
"depends": [
"jquery:$"
]
},
}
Take a look at this repo which I believe shows the fixed version of your app. The issue is that your app.js and utils.js modules aren't exporting anything to their respective require calls. One option is to add a line like:
module.exports = App;
to the bottom of your app.js file, and the equivalent to the bottom of your utils.js file. You'll see if you test the repo that badapp doesn't have this line and produces the exact behavior you're describing.
See this answer for an explanation of the issue.