Browserify Ember.js 1.7 - ember.js

The latest 1.7 Ember beta breaks my gulp-browserify task (config below) with the following exception:
Error: browserify-shim needs to be passed a proper browserify instance as the first argument.
Gulp had been browserifying Ember happily up until 1.7 (and continues to do so for latest 1.6 using the config below). I noticed in the release notes for 1.7 that the module system has undergone some upheaval.
My question is: Is this a legitimate bug in Ember (or perhaps Browserify)? Or is Ember no longer intended to be used with tools like browserify going forward, in favor of some other specific approach?
Exact config:
packages.json :
(Note, this particular site already has jQuery embedded via a standard script tag, hence the need for browserify-shim, and the global: notation on the jquery dep.)
{
"browser": {
"handlebars": "./scripts/lib/handlebars-v1.3.0.js",
"ember": "./scripts/lib/ember-1.7.min.js"
},
"browserify-shim": {
"jquery": "global:jQuery",
"handlebars": "Handlebars",
"ember": {
"exports": "Ember",
"depends": [
"handlebars:Handlebars"
]
}
},
"browserify": {
"transform": [
"browserify-shim"
]
},
"devDependencies": {
"browserify": "^4.1.11",
"browserify-shim": "^3.5.0",
"gulp": "^3.8.1",
"gulp-browserify": "^0.5.0"
}
}
gulpfile.js :
var gulp = require('gulp'),
browserify = require('gulp-browserify');
gulp.task('scripts', function () {
gulp.src([
'./app.js',
])
.pipe(browserify({
insertGlobals: false,
debug: false
})).pipe(gulp.dest('./Scripts/build'));
});
gulp.task('default', ['scripts']);
app.js :
var Ember = require('ember');
Basic Repro:
in a test dir:
npm install gulp browserify gulp-browserify browserify-shim
ensure paths exist to deps:
"handlebars": "./scripts/lib/handlebars-v1.3.0.js"
"ember": "./scripts/lib/ember-1.7.min.js"
add my example app.js above
add my packages.json above
add my gulpfile.js above
run gulp
Swap out Ember 1.7 for 1.6 to see success.
Thanks!

Related

Unable to instrument expo app with istanbul or cypress/instrument

I have been trying this for a while now, without success.
I have an expo app and I am using cypress to test some use cases using the web version of the app (generated by expo).
However, I would like to generate some code coverage as well. I have read the official documentation for it, that recommends to babel-plugin-istanbul do to so, but it does not seem to work with expo.
I am not sure why this would not work.
Edit
I removed the files previously pointed here as they were not important.
Thanks for a wonderful documentation provided by a hero without a cape, I figured that my settings were wrong.
All I needed to do was:
install babel-plugin-istanbul
Update babel.config.js
module.exports = {
presets: ['babel-preset-expo'],
plugins: [
'istanbul',
[
'module-resolver',
{
root: ['.'],
extensions: [
'.js',
],
alias: {
'#': './',
},
},
],
],
};
update cypress/support/index.js
import '#cypress/code-coverage/support';
update cypress/plugins/index.js
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config);
// add other tasks to be registered here
// IMPORTANT to return the config object
// with the any changed environment variables
return config;
};
and voilĂ !

How can i load changes to my code in a Vue app?

I deployed a Django+VueJS app that uses django webpack loader in order to render Vue apps in my Django templates. I used Nginx and Gunicorn to deploy the app to a DigitalOcean VPS, everything works without any problem but i have some doubts on how to edit my components in production, since i'm fairly new to Vue
Here is my vue.config:
const BundleTracker = require("webpack-bundle-tracker");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const pages = {
'main': {
entry: './src/main.js',
chunks: ['chunk-vendors']
},
}
module.exports = {
pages: pages,
runtimeCompiler: true,
filenameHashing: false,
productionSourceMap: false,
publicPath: process.env.NODE_ENV === 'production'
? 'static/vue'
: 'http://localhost:8080/',
outputDir: '../django_vue_mpa/static/vue/',
chainWebpack: config => {
config.optimization
.splitChunks({
cacheGroups: {
moment: {
test: /[\\/]node_modules[\\/]moment/,
name: "chunk-moment",
chunks: "all",
priority: 5
},
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "chunk-vendors",
chunks: "all",
priority: 1
},
},
});
Object.keys(pages).forEach(page => {
config.plugins.delete(`html-${page}`);
config.plugins.delete(`preload-${page}`);
config.plugins.delete(`prefetch-${page}`);
})
config
.plugin('BundleTracker')
.use(BundleTracker, [{filename: '../vue_frontend/webpack-stats.json'}]);
// Uncomment below to analyze bundle sizes
// config.plugin("BundleAnalyzerPlugin").use(BundleAnalyzerPlugin);
config.resolve.alias
.set('__STATIC__', 'static')
config.devServer
.public('http://localhost:8080')
.host('localhost')
.port(8080)
.hotOnly(true)
.watchOptions({poll: 1000})
.https(false)
.headers({"Access-Control-Allow-Origin": ["*"]})
}
};
So in order to deploy the Vue part i did npm run build and npm created a bunch of files in my static directory. Now, every time i edit a component, in order to see the changes on the web, i do npm run build every time, which takes some time. Is this how am i supposed to do it? Or is there a shorter way?
I don't know about django, But I know about vue..
is this how am I supposed to do it?
For me, I don't suggest it, you can use your django as a backend for your frontend
that should mean you would have 2 servers running. 1 for your django and 1 for your vue app. use XHR request to access your django App, remember to handle CORS. IMHO I don't want vue to be used as a component based framework.
is there a shorter way.
YES, and this is how you do it.
add to package.json
{
...,
scripts: {
...,
'watch' : 'vue-cli-service build --watch --inline-vue',
...,
}
}
while using the following settings in vue.config.js
module.exports = {
'publicPath': '/django/path/to/public/folder',
'outputDir': '../dist',
'filenameHashing': false,
runtimeCompiler: true,
'css': {
extract: true,
},
}
i forgot about how publicPath and outputDir works..
but you can check it out here https://cli.vuejs.org/config/#publicpath
regarding the code on the package.json file..
you can check it here
https://github.com/vuejs/vue-cli/issues/1120#issuecomment-380902334

How to perform unit tests for custom elements in Jest using JSDom

I realise that this question has been asked on a number of occasions, though the environment has changed since those questions where asked: notably, JSDom now supports custom elements.
These other questions revolved around seeking alternatives (such as using Happy Dom) as JSDom did not support custom elements at that time. However, now that JSDom does support custom elements, does anyone have any information that can solve the following error?
TypeError: Class constructor HTMLElement cannot be invoked without 'new'
1 | export default class Foo extends HTMLElement {
2 | constructor() {
> 3 | super();
| ^
4 |
5 | this._clicker = 2;
6 | }
at new Foo (__tests__/fooclass.js:3:5)
at Object.<anonymous> (__tests__/fooclass.test.js:7:13)
Current setup:
A reference repo is available here (now fixed):
Custom element example
class Foo extends HTMLElement {
constructor() {
super();
this._clicker = 2;
}
connectedCallback() {
this.textContent = 'My Foo Bar Element';
}
get testCallback() {
return 'hello world!';
}
set clicker(num) {
this._clicker = Number(num);
}
get clicker() {
return this._clicker;
}
}
packages.json
{
"scripts": {
"test": "jest --env=jest-environment-jsdom-sixteen"
},
"jest": {
"verbose": true
},
"devDependencies": {
"#babel/preset-env": "^7.8.4",
"babel-plugin-transform-builtin-classes": "^0.6.1",
"jest": "^25.1.0",
"jest-environment-jsdom-sixteen": "^1.0.2"
}
}
.babelrc
{
"presets": ["#babel/preset-env"]
}
NOTE: As of May 2020, Jest supports JSDom 16.* by default, rendering the below no longer necessary or relevant
Solution
Jest runs with JSDom ^15.1.1 by default (as of Feb 17th, 2020) so you will need to update manually to use JSDom 16.2.0 installing jest-environment-jsdom-sixteen.
First, install the latest JSDom environment for Jest
npm i jest-environment-jsdom-sixteen --save-dev
And change your package.json to include:
"scripts": {
"test": "jest --env=jest-environment-jsdom-sixteen"
},
This will ensure that Jest is running the correct environment.
You will also need to ensure that Babel correctly handles built-in classes (e.g. class HTMLElement {}) by installing babel-plugin-transform-builtin-classes, like so:
npm i babel-plugin-transform-builtin-classes --save-dev
And added to your .babelrc the following
"plugins": [
["babel-plugin-transform-builtin-classes", {
"globals": ["Array", "Error", "HTMLElement"]
}]
]
Do not install babel-plugin-transform-es2015-classes as this already forms part of the Babel 7 core, as per this issue
Working reduced test case available here.

My CSS made with Tailwind doesn't work on build with gridsome for netlify

When I build (netflify build) my Gridsome personal website, tailwind CSS classes doesn't work and the website look's like without CSS.
I have already tried to build without git, reinstall tailwind...
I show my gridsome config if that's the problem:
const tailwind = require('tailwindcss');
const purgecss = require('#fullhuman/postcss-purgecss');
const postcssPlugins = [
tailwind(),
]
if (process.env.NODE_ENV === 'production') postcssPlugins.push(purgecss());
module.exports = {
siteName: 'Zolder | Works',
plugins: [],
css: {
loaderOptions: {
postcss: {
plugins: postcssPlugins,
},
},
},
}
I had this issue as well. I used the Tailwind Plugin for Gridsome and it worked locally but when deploying to Netlify, the Tailwind css wasn't getting added.
Referencing this starter file: https://github.com/drehimself/gridsome-portfolio-starter/blob/master/src/layouts/Default.vue
I added the main.css with all the Tailwind imports file to the end of the Default Layout template instead, and this worked for me.
You can add Tailwind to your Gridsome project with these steps:
edit gridsome.config.js
module.exports = {
siteName: "Zolder",
plugins: [],
chainWebpack: config => {
config.module
.rule("postcss-loader")
.test(/.css$/)
.use(["tailwindcss", "autoprefixer"])
.loader("postcss-loader");
}
};
create a global.css file in ./src/styles
#tailwind base;
#tailwind components;
#tailwind utilities;
import global.css in main.js
import './styles/global.css'

How to access Vuejs methods to test with Jest?

I have the following file: deposit-form.js.
With the following code:
new Vue({
el: '#app',
data: {
title: 'title',
depositForm: {
chosenMethod: 'online',
payMethods: [
{ text: 'Already paid via Venmo', value: 'venmo' },
{ text: 'Pay online', value: 'online' },
{ text: 'In-person payment', value: 'person' }
],
},
},
methods: {
submitDeposit: function() {
$.ajax({
url: 'http://localhost:8000/api/v1/deposit/',
type:'post',
data: $('#deposit-form').serialize(),
success: function() {
$('#content').fadeOut('slow', function() {
// Animation complete.
$('#msg-success').addClass('d-block');
});
},
error: function(e) {
console.log(e.responseText);
},
});
},
showFileName: function(event) {
var fileData = event.target.files[0];
var fileName = fileData.name;
$('#file-name').text('selected file: ' + fileName);
},
},
});
I'm having problems on how to setup Jest, how to import the VueJs functions inside 'methods' to make the tests with Jest.
How should be my code on the deposit-form.test.js ?
The first thing you need to do is export Vue app instance.
// deposit-form.js
import Vue from 'vue/dist/vue.common';
export default new Vue({
el: '#app',
data: {...},
...
});
Now you can use this code in your spec file. But now you need to have #app element before running tests. This can be done using the jest setup file. I will explain why it's needed. When you import your main file (deposit-form.js) into a test, an instance of Vue is created in your main file with new. Vue is trying to mount the application into #app element. But this element is not in your DOM. That is why you need to add this element just before running the tests.
In this file you also can import jQuery globally to use it in your tests without import separately.
// jest-env.js
import $ from 'jquery';
global.$ = $;
global.jQuery = $;
const mainAppElement = document.createElement('div');
mainAppElement.id = 'app';
document.body.appendChild(mainAppElement);
Jest setup file must be specified in the jest configuration section in package.json.
// package.json
{
...,
"dependencies": {
"jquery": "^3.3.1",
"vue": "^2.6.7"
},
"devDependencies": {
"#babel/core": "^7.0.0",
"#babel/plugin-transform-modules-commonjs": "^7.2.0",
"#babel/preset-env": "^7.3.4",
"#vue/test-utils": "^1.0.0-beta.29",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^24.1.0",
"babel-loader": "^8.0.5",
"babel-preset-vue": "^2.0.2",
"jest": "^24.1.0",
"vue-jest": "^3.0.3",
"vue-template-compiler": "^2.6.7",
"webpack": "^4.29.5",
"webpack-cli": "^3.2.3"
},
"scripts": {
"test": "./node_modules/.bin/jest --passWithNoTests",
"dev": "webpack --mode development --module-bind js=babel-loader",
"build": "webpack --mode production --module-bind js=babel-loader"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
"setupFiles": [
"<rootDir>/jest-env.js"
]
}
}
Also, you probably need to configure Babel to use the features of ES6 in your projects and tests. This is not necessary if you follow the commonjs-style in your code. Basic .babelrc file contains next code:
// .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "entry",
"targets": {
"browsers": [
"last 2 versions"
]
}
}
],
"vue",
],
"plugins": [
"#babel/plugin-transform-modules-commonjs",
]
}
Now you can write your tests.
// deposit-form.test.js
import App from './deposit-form';
describe('Vue test sample.', () => {
afterEach(() => {
const mainElement = document.getElementById('app');
if (mainElement) {
mainElement.innerHTML = '';
}
});
it('Should mount to DOM.', () => {
// Next line is bad practice =)
expect(App._isMounted).toBeTruthy();
// You have access to your methods
App.submitDeposit();
});
});
My recommendation is to learn Vue Test Utils Guides and start to divide your code into components. With the current approach, you lose all the power of components and the ability to test vue-applications.
I updated my answer a bit. As I understood from the comment to the answer, you connect the libraries on the page as separate files. Here is my mistake. I didn't ask if the build system is being used. Code in my examples is written in the ECMA-2015 standard. But, unfortunately, browsers do not fully support it. You need an transpiler that converts our files into a format that is understandable for browsers. It sounds hard. But it's not a problem. I updated the contents of the file package.json in response. Now it only remains to create an input file for the assembly and run the assembly itself.
The input file is simple.
// index.js
import './deposit-form';
The build is started with the following commands from terminal.
# for development mode
$ yarn run dev
# or
$ npm run dev
# for production mode
$ yarn run build
# or
$ npm run build
The output file will be placed in the directory ./dist/. Now instead of separate files you need to connect only one. It contains all the necessary for the library and your code.
I used webpack to build. More information about it can be found in the documentation. Good example you can find in this article.