Custom build for Dojo 1.7.1 with Layer and CSS Optimization - build

With Dojo 1.6.x it was quite easy to create a custom build. In the end I only needed to include a dojo.js file, my application layer file and an optimized css file with all the styles. Simple and easy.
But with Dojo 1.7.x I don't get it. My goal is just to include an opmtimized dojo.js file, my application layer file with all my widgets and stuff and an optmized css file.
Here is my profile.js
var profile = {
releaseDir: "./release",
basePath: "..",
action: "release",
cssOptimize: "comments",
mini: true,
optimize: "closure",
layerOptimize: "closure",
stripConsole: "all",
selectorEngine: "acme",
packages:[
{
name: "dojo",
location: "./sources/dojo"
},
{
name: "dijit",
location: "./sources/dijit"
},
{
name: "dojox",
location: "./sources/dojox"
}
],
layers: {
"dojo/dojo": {
name: "myDojo.js",
include: [ "dojo/dojo" ],
boot: true,
dependencies: [ "dojo/parser", "dojo/data/ItemFileReadStore", "dijit/themes/tundra", "dijit/Dialog", "dijit/form/Form", "dijit/form/Button", "dijit/form/CheckBox", "dijit/form/ComboBox", "dijit/form/DateTextBox", "dijit/form/FilteringSelect", "dijit/form/NumberSpinner", "dijit/form/Textarea", "dijit/form/TextBox", "dijit/form/TimeTextBox", "dijit/form/ValidationTextBox", "dijit/layout/ContentPane", "dijit/layout/TabContainer", "dijit/Tooltip", "dojox/widget/ColorPicker" ]
}
},
resourceTags: {
amd: function (filename, mid) {
return /\.js$/.test(filename);
}
}
};
When I run the build a release is created. I found the dojo.js which has the size of about 580 KB uncompressed. But I did not fond my application file and the compressed css file with all styles.
What am I doing wrong?
Thanks, Ralf

Your layer specification seems to be incorrect. Try this instead:
layers: {
"dojo/myDojo": {
include: [ "dojo/parser", "dojo/data/ItemFileReadStore",
"dijit/themes/tundra", "dijit/Dialog", "dijit/form/Form",
"dijit/form/Button", "dijit/form/CheckBox",
"dijit/form/ComboBox", "dijit/form/DateTextBox",
"dijit/form/FilteringSelect", "dijit/form/NumberSpinner",
"dijit/form/Textarea", "dijit/form/TextBox",
"dijit/form/TimeTextBox", "dijit/form/ValidationTextBox",
"dijit/layout/ContentPane", "dijit/layout/TabContainer",
"dijit/Tooltip", "dojox/widget/ColorPicker"
],
boot: true
}
},
References
http://dojotoolkit.org/reference-guide/1.7/build/
http://dojotoolkit.org/documentation/tutorials/1.7/build/

Related

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.

React+Typescript+Webpack4: Cannot find module '***.json'

I am trying to import the data from a .json file in a .tsx using following:
import data from "data/mockup.json"
but I got the error
Cannot find module 'data/mockup.json'
My webpack config looks like this:
const babelLoader = {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
["#babel/preset-env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
},
"modules": true
}]
]
}
};
module.exports = {
entry: {...},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
alias: {
data: path.resolve(__dirname, 'src/app/data')
}
},
output: {...},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
babelLoader,
{
loader: 'ts-loader'
}
]
},
{
test: /\.js$/,
exclude: /node_modules\/(?!(dom7|swiper)\/).*/,
use: [
babelLoader
]
}
]
},
...
}
enter code here
I think the .json is built in webpack4 by default so there may be something wrong with my webpack config?
Version used:
webpack: v4.4.1
typescript: 2.7.2
declare module in d.ts file
declare module "*.json"
Add a field in tsconfig.json in compiler options
"typeRoots": [ "node_modules/#types", "./typings.d.ts" ],
Now import into file (.tsx)
import * as data from "./dat/data.json";
Webpack#4.4.1 and Typescript#2.7.2
Hope this helps!!!
Ref1: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
Ref2: https://github.com/Microsoft/TypeScript-React-Starter/issues/12
Although answers are helpful to load the JSON file as a module, they are limited in many aspects
First: the typescript can load by default JSON files, you only need to add into tsconfig.json below line:
{
...
"resolveJsonModule": true,
...
}
second: the suggested solution will enable implicitly for type check and auto-completion
P.S. the attached image is from a tutorial that talks about the same subject click here to check more
Personnaly, uncommenting :
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
in the file tsconfig.json did the trick.
I found the hint here.

Webpack TypeScript and xgettext translations

I have a Django app and am using Django's i18n module to help translating my strings. For translating JavaScript, I run
python manage.py makemessages -d djangojs
which adds all marked strings to a .po file. This works quite well for all my boring .js files in my static folder. However, we are starting to use webpack to pack some typescript (.tsx files) into a bundle.js file. This file is copied to the static folder after building, so I expected Djangos makemessages to pick up the strings from it as well. However, it seems that the strings are not parsed correctly, because most of the code in bundle.js is simply strings wrapped in eval().
I believe this means that I need webpack to - in addition to the bundle.js file - create a .js file for each .tsx file without all of the eval() nonsense, so that django's makemessages can parse it properly. I have no idea how to do this, however. My current config looks like this
var path = require("path");
var WebpackShellPlugin = require('webpack-shell-plugin');
var config = {
entry: ["./src/App.tsx"],
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js"
},
devtool: 'source-map',
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/
},
{
test: /\.scss$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
},
plugins: [
new WebpackShellPlugin({
onBuildEnd:['./cp_to_static.sh'],
dev: false // Needed to trigger on npm run watch
})
]
};
module.exports = config;
So how can I make webpack spit out these files?
Is this the right thing to do, or is there a way to make Django parse bundle.js properly?
Turns out that all of the eval nonsense was generated by webpacks "watch" function. When simply running webpack for building the script, it works as expected

Dojo build requesting already inlined templates

I'm hopelessly trying to make the Dijit template inlining functionality of Dojo builds for my AMD project work with no luck yet ...
The particular issue isn't the inlining of the HTML templates themselves, but the fact that they are still requested with Ajax (XHR) after being successfully inlined.
Templates are inlined the following way :
"url:app/widgets/Example/templates/example.html": '<div>\n\tHello World!</div>'
The Dijit widget itself, after building, defines templates like this :
define("dojo/_base/declare,dijit/_Widget,dojo/text!./templates/example.html".split(","), function (f, g, d) {
return f("MyApp.Example", [g], {
templateString: d,
});
});
I tried to build with :
the shrinksafe / closure optimiser
relative / absolute paths
using the old cache() method
using the templatePath property
but even after having run a successful build (0 errrors and a few warnings) where the templates were inlined, Dojo / Dijit still makes Ajax requests to these resources.
Here is my build profile :
var profile = {
basePath: '../src/',
action: 'release',
cssOptimize: 'comments',
mini: true,
optimize: 'closure',
layerOptimize: 'closure',
stripConsole: 'all',
selectorEngine: 'acme',
internStrings: true,
internStringsSkipList: false,
packages: [
'dojo',
'dijit',
'dojox',
'app'
],
layers: {
'dojo/dojo': {
include: [
'app/run'
],
boot: true,
customBase: true
},
},
staticHasFeatures: {
'dojo-trace-api': 0,
'dojo-log-api': 0,
'dojo-publish-privates': 0,
'dojo-sync-loader': 0,
'dojo-xhr-factory': 0,
'dojo-test-sniff': 0
}
};
Due to this issue my application is completely unusable because there are so many files to download separately (browsers have a limit on the number of parallel connections).
Thank you very much in advance !
UPDATE :
The two lines loading dojo.js and the run.js in my index.html :
<script data-dojo-config='async: 1, tlmSiblingOfDojo: 0, isDebug: 1' src='/public/dojo/dojo.js'></script>
<script src='/public/app-desktop/run.js'></script>
Here is the new build-profile :
var profile = {
basePath: '../src/',
action: 'release',
cssOptimize: 'comments',
mini: true,
internStrings: true,
optimize: 'closure',
layerOptimize: 'closure',
stripConsole: 'all',
selectorEngine: 'acme',
packages : [
'dojo',
'dijit',
'app-desktop'
],
layers: {
'dojo/dojo': {
include: [
'dojo/request/xhr',
'dojo/i18n',
'dojo/domReady',
'app-desktop/main'
],
boot: true,
customBase: true
}
},
staticHasFeatures: {
'dojo-trace-api': 0,
'dojo-log-api': 0,
'dojo-publish-privates': 0,
'dojo-sync-loader': 0,
'dojo-xhr-factory': 0,
'dojo-test-sniff': 0
}
};
My new run.js file :
require({
async: 1,
isDebug: 1,
baseUrl: '/public',
packages: [
'dojo',
'dijit',
'dojox',
'saga',
'historyjs',
'wysihtml5',
'app-shared',
'jquery',
'jcrop',
'introjs',
'app-desktop'
],
deps: [
'app-desktop/main',
'dojo/domReady!'
],
callback: function (Main) {
debugger;
var main = new Main();
debugger;
main.init();
}
});
and my main.js file looks like this :
define([
'dojo/_base/declare',
'app-desktop/widgets/Application',
'app-desktop/config/Config',
'saga/utils/Prototyping',
'dojo/window',
'dojo/domReady!'
], function (declare, Application, ConfigClass, Prototyping, win) {
return declare([], {
init: function() {
// ... other stuff
application = new Application();
application.placeAt(document.body);
// ... some more stuff
}
});
});
In build-mode, I get the following error :
GET http://localhost:4000/app-desktop/run.js 404 (Not Found)
which is weird because it means that the build process made it so that dojo has an external dependency rather than an a already inlined dojoConfig variable in the builded file.
In normal-mode, files get requested, but the app is never created.
In both cases none of the two debuggers set in the run.js file were run which means that the callback method was never called for some reason.
Thank you for your help !
I've printed values of requireCacheUrl and require.cache to console in the method load() of dojo/text.js. At least in my case, keys of my templates in the cache differs from lookup keys on one leading slash.
For example, I have "dojo/text!./templates/Address.html" in my widget. It present with key url:/app/view/templates/Address.html in the cache but is searched like url:app/view/templates/Address.html, causing cache miss and xhr request.
With additional slash in dojo/text.js (line 183 for version 1.9.1) it seemingly works (line would looks like requireCacheUrl = "url:/" + url).
Not sure what kind of bugs this "fix" could introduce. So, it probably worth to report this issue to dojo folks.
UPD: Well, I see you've already reported this issue. Here is the link: https://bugs.dojotoolkit.org/ticket/17458.
UPD: Don't use hack described above. It was only attempt to narrow issue. Real issue in my project was with packages and baseUrl settings. Initially I created my project based on https://github.com/csnover/dojo-boilerplate. Then fixed it as in neonstalwart's sample.
This sounds like https://bugs.dojotoolkit.org/ticket/17141. If it is, you just need to update to Dojo 1.9.1.

Including dependencies in a Dojo build

Despite using the Dojo build system, my app is still including a large number of javascript files which I would have hoped to be covered by the build.
Here's my build profile:
var profile = (function(){
return {
basePath: "./",
releaseDir: "release",
action: "release",
selectorEngine: "acme",
cssOptimize: "comments.keepLines",
packages:[{
name: "dojo",
location: "dojo"
},{
name: "dijit",
location: "dijit"
},{
name: "dojox",
location: "dojox"
},{
name: "my",
location: "my"
}],
layers: {
"my/admin": {
include: ['dojo/ready', 'dojo/dom', 'dojo/query', 'dojo/request/xhr', 'my/Form', 'my/Tree/Radio']
}
}
};
})();
The app is still including the following JS files on each request: my/Form.js (even though this is listed in the profile), dojo/fx/Toggler.js, dijit/_base.js, dijit/WidgetSet.js, dijit/_base/focus.js, dijit/_base/place.js, dijit/place.js, dijit/_base/popup.js, dijit/popup.js, dijit/BackgroundIframe.js, dijit/_base/scroll.js, dijit/_base/sniff.js, dijit/_base/typematic.js, dijit/typematic.js, dijit/_base/wai.js, dijit/_base/window.js.
my/Tree/Radio extends dijit/Tree, so I'm assuming a lot of the files above are dijit base files that are being loaded automatically by dijit.Tree. But surely the build tool should resolve dependencies like this and include them in the 'built' file?
I am using Dojo 1.8.3.
In dojo/fx, it dynamically looks up the Toggler with the comment
use indirection so modules not rolled into a build
Not sure why, but if you add dojo/fx/Toggler to the include of your build script, it should not make the additional xhr requests.
EDIT: Apparently dijit/Widget does something similar with dijit/_base, so you will want to add that to the includes as well.
http://trac.dojotoolkit.org/ticket/14262