relative path doesn't work with paths - path

I'm having a problem with relative paths in requirejs.
First of all, I have the following structure. I'm running it with a virtual host (os.com) and the path is os.com/test
index.html
<script data-main="config" src="require.js"></script>
config.js
require.config({
baseUrl: "./apps",
deps: ['ui'],
paths: {
ui: 'ui/ui',
system: 'system/system',
core: 'core/core'
}
});
ui.js
define(['./class/menuBuilder',"./class/window"], function(menuBuilder, windowBuilder){
return {
menuBuilder: menuBuilder,
windowBuilder: windowBuilder
}
});
When I run it, I get the following errors.
GET http://os.com/test/apps/class/menuBuilder.js 404 (Not Found)
GET http://os.com/test/apps/class/window.js 404 (Not Found)
If I take out 'ui' property from the 'paths' property then change deps to ['ui/ui'], it works, but I would like to use paths.
Changed config.js
require.config({
baseUrl: "./apps",
deps: ['ui/ui'],
paths: {
system: 'system/system',
core: 'core/core'
}
});
How do I change my config to make paths and relative path work together?

I had similar problem. I didn't have deps:'ui' part in my configuration, just the path setting, but still the relative module reference ('./class/menuBuilder') would not work from the module loaded with path ("ui: 'ui/ui'") and would use baseUrl instead. To solve it, I defined 'ui' as a package:
require.config({
baseUrl: "./apps",
deps: ['ui'],
paths: {
system: 'system/system',
core: 'core/core'
},
packages : [
{
name: 'ui',
location : 'ui',
main : 'ui'
},
]
});
In this case require will load relatively-pathed modules correctly.
Here is a useful post: Relative paths with RequireJS modules/packages

The solution here is to use map configuration, not paths configuration. Paths configurations should only be used for folders, not modules themselves. Map configurations apply to individual modules.
So try:
require.config({
map: {
'*': {
'ui': 'ui/ui'
}
}
});

Related

Rollup configuring alias for semantic-ui-less #import

I have been configuring rollup for creating custom react component library on top of fomantic-ui.
I have already setup the rollup.config.js
ALthough in the configuration, I need to resolve an import:
#import (multiple) '../../theme.config';
the import is part of fomantic-ui-less library, which needs to be resovled to:
path.join(__dirname, '/themes/theme.config')
and I do have themes/theme.config at my project root.
when I run build command it throws following error:
[!] (plugin postcss) Error: '../../theme.config' wasn't found. Tried - E:\Projects\UILibrary\node_modules\fomantic-ui-less\theme.config,..\..\theme.config
and I have used the rollup-plugin-postcss plugin and #rollup/plugin-alias, and called it inside plugins array
...
plugins: [
...
alias({
entries: [
find: '../../theme.config$',
replacement: path.join(__dirname, '/themes/theme.config')
]
})
postcss(),
...
]
I have also tried changing the order of plugins.
And the worst part is, it is working when configuring the storybook, using webpack alias.
.storybook/main.js
webpackFinal: async (config) => {
config.resolve.alias = {
"../../theme.config$": path.join(__dirname, "../themes/theme.config")
}
...
}

How can I easily reference separate js / css files for debugging when using gulp or grunt?

I'm developing a legacy ASP.NET MVC 5 project which still uses ASP.NET Bundling and Minification. I'm interested in switching to Gulp or Grunt, because I need to save source maps for my js files.
It seems easy to generate a minified script bundle with Gulp or Grunt, but what I do not understand yet is the recommended setup for loading single js files when debugging and minified bundles in production. I guess it would be quite easy to generate a razor view for including the scripts as part of my Grunt / Gulp compilation process, but it feels like re-inventing the wheel.
For instance, in ASP.NET MVC i can write something like this:
#Scripts.Render("~/bundles/MyJSBundle")
and it will automatically load separate js files in development and a single script bundle in production. What is the easiest way achieve this with Gulp or Grunt?
Short answer:
Typically when using Grunt you generate two builds - one for "dev" (development) and another for "dist" (distribution/production). Whereby for the scenario you've described;
Both the "dev" and "dist" builds generate a single concatenated/minified file version (e.g. bundle.min.js) derived from multiple source .js files.
However, only the "dev" build generates an additional Source Map file(s), that holds information about your original .js files, for the purpose of debugging during the development lifecycle.
Grunt plugins, such as grunt-processhtml, provide a way to update any links to .js assets in the .html file. For example, let's say your source .html contains these two links;
<script src="js/a.js"/>
<script src="js/b.js"/>
They can be substituted during the "dist" and/or "dev" build step to the following single <script> element:
<script src="dir/bundle.min.js"/>
Example demo:
The following somewhat contrived example demonstrates how you may approach your requirement using Grunt.
Let's say our initial project directory is structured as follows:
project
├── Gruntfile.js
├── node_modules
│   └── ...
├── package.json
└── src
├── index.html
└── js
├── a.js
└── b.js
Note, in the src directory we have a single index.html file, and two .js files in the js directory.
In the contents of index.html shown below it contains two <script> elements, each one referencing a .js file.
project/src/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>demo</title>
</head>
<body>
<!--build:js js/bundle.min.js-->
<script src="js/a.js"></script>
<script src="js/b.js"></script>
<!--/build-->
</body>
</html>
Note, the custom HTML comments encasing both <script> elements. These custom HTML comments are utilized by grunt-processhtml. The part that reads; js/bundle.min.js in the comment essentially defines the new pathname to be used.
Let's consider the following Gruntfile.js configuration:
Gruntfile.js
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-processhtml');
grunt.initConfig({
// 1. Concatenate .js files.
concat: {
dist: {
src: [
'src/js/a.js',
'src/js/b.js'
],
dest: './dist/js/bundle.min.js'
},
dev: {
options: {
sourceMap: true
},
src: [
'src/js/a.js',
'src/js/b.js'
],
dest: './dev/js/bundle.min.js'
}
},
// 2. Minify .js files.
uglify: {
dist: {
files: {
'./dist/js/bundle.min.js': './dist/js/bundle.min.js' // dest : src
}
},
dev: {
options: {
mangle: false,
sourceMap: true,
sourceMapIn: './dev/js/bundle.min.js.map'
},
files: {
'./dev/js/bundle.min.js': './dev/js/bundle.min.js' // dest : src
}
}
},
// 2. Process .html file.
processhtml: {
dist: {
files: {
'./dist/index.html': './src/index.html' // dest : src
}
},
dev: {
files: {
'./dev/index.html': './src/index.html' // dest : src
}
}
}
});
grunt.registerTask('default', ['dist', 'dev']);
grunt.registerTask('dist', [
'concat:dist',
'uglify:dist',
'processhtml:dist'
]);
grunt.registerTask('dev', [
'concat:dev',
'uglify:dev',
'processhtml:dev'
]);
};
Explanation of Gruntfile.js:
In addition to the previously mentioned grunt-processhtml plugin the following two are also utilized in this example:
grunt-contrib-concat - for concatenating the two .js files.
grunt-contrib-uglify - for minifying the .js file.
Note: There are other plugins available for these types of task. I have chosen these additional two plugins for the purpose of this demonstration.
Each of the three Tasks (concat, uglify, and processhtml) contain two separate Targets named dist and dev. The main differences in each Target are:
Different dest (destination) paths for the resultant generated .jsfile(s).
For the concat:dev and uglify:dev Targets its options object defines the configuration for the resultant Source Map file.
At the end of Gruntfile.js three different grunt.registerTask() have been defined. Each one defines a taskList that essentially defines which Task and Target to run in the order specified.
For example consider the following registered task named dist:
grunt.registerTask('dist', [
'concat:dist',
'uglify:dist',
'processhtml:dist'
]);
When running grunt dist via the command line Grunt essentially invokes this Task, which subsequently performs the following in this order:
Firstly, runs the dist Target defined in the concat Task.
Then runs the dist Target defined in the uglify Task.
Finally, runs the dist Target defined in the processhtml Task.
Running Gruntfile.js (above) and its output
Running the following command via the command line:
grunt dev
outputs the following additional assets to the project directory:
project
├── ...
├── dev
│   ├── index.html
│   └── js
│   ├── bundle.min.js
│   └── bundle.min.js.map
└── ...
As you can see it has:
Created a new dev folder in the root of the project directory.
The two <script> elements originally defined in project/src/index.html have been substituted in the newly generated project/dev/index.html with a single <script> tag as follows:
<script src="js/bundle.min.js"></script>
Both files; project/src/js/a.js and project/src/js/b.js, have been concatenated and minified in the resultant project/dev/js/bundle.min.js.
The following source map file has been generated; project/dev/js/bundle.min.js.map. This file essentially maps back to the original project/src/js/a.js and project/src/js/b.js files.
Running the following command via the command line:
grunt dist
outputs the following additional assets to the project directory:
project
├── ...
├── dist
│ ├── index.html
│ └── js
│ └── bundle.min.js
└── ...
As you can see this time it has;
Created a dist folder in the root of the project directory.
Again, the two <script> elements originally defined in project/src/index.html have been substituted in the newly generated project/dist/index.html with a single <script> tag (as per the aforementioned dev Task).
Again, both files; project/src/js/a.js and project/src/js/b.js, have been concatenated and minified in the resultant project/dist/js/bundle.min.js.
However, the main notable difference is that NO source map file has been created.
Running the following command via the command line:
grunt
will produce both the outputs defined in the previous steps 1 and 2.

How to create a PDF on Node.js using PDFMake and vfs_fonts?

It looks like this question has been asked quite a few times with older versions of PDFMake, but hasn't been updated with what appears to be the latest directory structure. Plus, copying fonts into a root "fonts" folder isn't great.
How in the world do I get a server side version of PDFMake ("pdfmake": "^0.1.31") running on Node.js with the included vfs_fonts.js file?
Install using npm on command line
npm install pdfmake fs --save
Boot up a Node.js app index.js with the following:
var fonts = {
Roboto: {
normal: 'fonts/Roboto-Regular.ttf',
bold: 'fonts/Roboto-Medium.ttf',
italics: 'fonts/Roboto-Italic.ttf',
bolditalics: 'fonts/Roboto-MediumItalic.ttf'
}
};
var PdfPrinter = require('pdfmake/src/printer');
var printer = new PdfPrinter(fonts);
var dd = {
content: [
'First paragraph',
'Another paragraph'
]
}
var pdfDoc = printer.createPdfKitDocument(dd);
pdfDoc.pipe(fs.createWriteStream('basics.pdf')).on('finish',function(){
//success
});
pdfDoc.end();
Hit run and bam:
/usr/local/bin/node index.js
fs.js:640
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT: no such file or directory, open 'fonts/Roboto-Regular.ttf'
at Error (native)
at Object.fs.openSync (fs.js:640:18)
The problem seems to lie with the location of the fonts/Roboto... files. Client-side, this is solved by including the vfs_fonts.js file. Server-side, I'm not sure. There are NO fonts folder or .ttf files included. The meteor framework example I've found doesn't seem applicable.
Any ideas? All the official examples reference a src/fonts folder. Not a good way to go for an npm install server module.
This is what I did to resolve this.
Downloaded "roboto-font": "0.1.0" module and assign path of that fonts in Roboto object and it worked fine.
let fonts = {
Roboto: {
normal: 'node_modules/roboto-font/fonts/Roboto/roboto-regular-webfont.ttf',
bold: 'node_modules/roboto-font/fonts/Roboto/roboto-bold-webfont.ttf',
italics: 'node_modules/roboto-font/fonts/Roboto/roboto-italic-webfont.ttf',
bolditalics: 'node_modules/roboto-font/fonts/Roboto/roboto-bolditalic-webfont.ttf'
}
};
let printer = new pdfMake(fonts);
let pdfDoc = printer.createPdfKitDocument(pdfData);
pdfDoc.pipe(fs.createWriteStream(reportName));
pdfDoc.end();
You need to download first the Roboto font here https://fonts.google.com/specimen/Roboto
and copy them inside you fonts folder.
Update your fonts object like this:
var fonts = {
Roboto: {
normal: path.join(__dirname, '..', 'your_public_folder', '/fonts/Roboto-Regular.ttf'),
bold: path.join(__dirname, '..', 'your_public_folder', '/fonts/Roboto-Medium.ttf'),
italics: path.join(__dirname, '..', 'your_public_folder', '/fonts/Roboto-Italic.ttf'),
bolditalics: path.join(__dirname, '..', 'your_public_folder', '/fonts/Roboto-MediumItalic.ttf')
}
}
In this example, replace the 'your_public_folder' with folder name where you have all your html, css and js files.

Having trouble setting up ngtemplate-loader and webpacker

I've tried setting up the webpack loader by adding this to the webpack/loaders directory
var path = require('path');
module.exports = {
test: /\.html$/,
loaders: [`ngtemplate?relativeTo=${path.join(__dirname, "/app")}`, "html"] //html?attrs[]=div:ng-include
}
and then requiring the appropriate template file from the .js code.
templateUrl: require('ngtemplate!html!./app/views/environment/index.html')
but I get the following error
Module not found: Error: Can't resolve 'html' in '/Users/joe/testrails5.1/app/javascript/app/scripts'
resolve 'html' in '/Users/joe/testrails5.1/app/javascript/app/scripts'
Parsed request is a module
Does this work for anyone else? I'm using angular 1.6 so do I need to use a different module?

how to deploy your dart app (using Web ui) without using Pub Deploy

What is the best strategy to deploy a Dart Web-ui app manually ?
pub deploy doesn't work for me and I have raised bug report. So am thinking what is the best way to manually deploy.
This is how I started:
1) From project root I compile the webui components (dwc.dart)
2) change directory to web/out then run dart2js
3) copy all .js files into that scripts/js public folder on server
4) copy appname.html to server changing css and script paths to option 3
5) Make sure dart.js is also in the same directory as item 3
this is as far as I got. So what else do I need to do ?
A few questions:
1) Do I manually change the file paths in the generated .js files to point to public folders on server for the files they are referencing and make sure those files are on server also ?
2) Do I need to copy all packages to server also ?
3) Any preferred file structure on server?
Any tips on this really appreciated.
Thanks.
I wrote a Grunt script for it (since I had no time to look up how to properly write code for Grunt, I did not share the code since it's a mess) but I basically do this:
compiling a list of files with dwc to a given out dir
compile it to javascript
clean up all non-deployable files
change some paths inside the HTML to match the server paths (for some reasons, this gets changed by the compilation process)
remove all packages except the ones I really need (JS interopt and browser)
Since I'm only using the JS version, I remove all dart packages. Since the paths inside the HTML files are up to you, you can already use a structure that suits you/your server.
I can provide you with a Grunt script to understand the order of tasks. Practically the order I use is this one:
Create the build directory. I usually use /build/web. I usually create these files (index.html, main.dart, /css and so on into the /web dir). I create the rest of components into /lib directory.
Compile the .dart file that contains the main() function ("main.dart" in my case for simpler projects) file to Javascript and put it into /build/web directory
Copy the other needed files and folders to the /build/web directory. Also, during this process you'll be copying the packages that your project needs. You'll see in the example provided below.
Remove all empty folders from the project
You can create a Grunt task to open the /index.html file in the browser once the building process has ended (I will not provide this example)
The structure of the dart test project:
testApp
- gruntfile.js
- package.js
/lib
/packages
/angular
/web
- index.html
- main.dart
/css
/img
So, the Grunt example script to cover steps from 1 - 4 looks like this (copy it to gruntfile.js):
module.exports = function (grunt) {
grunt.initConfig({
// 1.
// create build web directory
mkdir: {
build: {
options: {
create: ['build/web']
}
}
},
// 2.
// compile dart files
dart2js: {
options: {
// use this to fix a problem into dart2js node module. The module calls dart2js not dart2js.bat.
// this is needed for Windows. So use the path to your dart2js.bat file
"dart2js_bin": "C:/dart/dart-sdk/bin/dart2js.bat"
},
compile: {
files: {'build/web/main.dart.js': 'web/main.dart'}
}
},
// 3.
// copy all needed files, including all needed packages
// except the .dart files.
copy: {
build: {
files: [
{
expand: true,
src: [
'web/!(*.dart)',
'web/css/*.css',
'web/res/*.svg',
'web/packages/angular/**/!(*.dart)',
'web/packages/browser/**/!(*.dart)'
],
dest: 'build'
}
]
}
},
// 4.
// remove empty directories copied using the previous task
cleanempty: {
build: {
options: {
files: false
},
src: ['build/web/packages/**/*']
}
},
});
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.registerTask('default', [
'mkdir:build',
'dart2js',
'copy:build',
'cleanempty:build'
]);
};
So this is the Grunt script example.
Create a /gruntfile.js file into your project's root directory and copy/paste the script to it.
Create a /package.json file into your project's root directory and copy/paste the following script:
{
"name": "testApp",
"version": "0.0.1",
"description": "SomeDescriptionForTheTestApp",
"main": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "YourName",
"peerDependencies": {
"grunt-cli": "^0.1.13"
},
"devDependencies": {
"grunt": "^0.4.5",
"grunt-cleanempty": "^1.0.3",
"grunt-contrib-copy": "^0.7.0",
"grunt-dart2js": "0.0.5",
"grunt-mkdir": "^0.1.2",
"matchdep": "^0.3.0"
}
}
Open Command Prompt in Windows, Terminal in Linux, navigate to your project's root directory and use this command:
npm install
Wait untill all Grunt modules needed will be downloaded to your local project. Once this is finished, issue this command in Command Prompt or Terminal:
node -e "require('grunt').cli()"
You can use this to initiate Grunt default task without having Grunt installed globally on your system.
Now, to know the exact build structure for your project (including the packages that the project needs), make a build using Pub Build. Then you will be able to instruct Grunt to create the same dir structure.
You can add other tasks (like minification) if you want.
Hope this will help you all to understand the process and get you started with a test app first. Add your comments to make this even better and simplify it even more.

Resources