so I am using angular2 / TypeScript and trying to convert this call which works fine today by the way:
window['Highmaps'] = require('highcharts/modules/map')(Highcharts);
to es6
something to the sorts of:
import * as Ng2Highcharts from 'highcharts/modules/map';
Ng2Highcharts(Highcharts)
but no luck as the former works but the es6 version does not.
this is the project by the way: https://github.com/Bigous/ng2-highcharts
and I have to convert it since I am trying to move from commonjs to systemjs,
thanks for any help,
Sean.
window['Highmaps'] = require('highcharts/modules/map')(Highcharts);
The value of the require is immediately applied as a function. This typically implies there's a default export that's being used.
Try
import Ng2Highcharts from 'highcharts/modules/map';
Ng2Highcharts(Highcharts)
To be able to import like that you need to create an entry in the system.config.js file or just System.config({...}), however you are doing the config.
One entry goes in the map and one in packages like this
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'rxjs': 'node_modules/rxjs',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'#angular': 'node_modules/#angular',
'highcharts': 'path/to/highcharts-directory'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
'highcharts/modules/map': { defaultExtension: 'js' }
};
And you're good to go.... Hope it works.
Related
I'm trying to generate two bundles (only two) using Rollup.js:
commonBundle.js
bundle2.js
bundle2.js depends on commonBundle.js.
The current result of rollup -c is actually 3 files instead of the 2 I want:
commonBundle.js
bundle2.js
commonDep-6c053814.js
Yes, commonDep.ts is indeed used by both commonBundle.ts and bundle2.ts. But since bundle2.ts depends on commonBundle.ts I was expecting the common dependency (commonDep.ts) to be included in the resulting commonBundle.js, not to be a separate bundle!
Is there a way to make all shared dependencies to be bundled inside a single bundle that needs to be imported by the others?
rollup.config.mjs :
export default {
input: {
commonBundle: "./src/commonBundle.ts",
bundle2: "./src/bundle2.ts"
},
output: {
dir: "./public",
format: "es"
},
plugins: [resolve({ browser: true }), commonjs(), typescript()]
};
commonBundle.ts :
import { sayHello } from "./commonDep";
export * from "./commonDep"; // export all common dependencies!
export function commonBundleFunction() {
sayHello("from common bundle");
}
bundle2.ts :
import "./commonBundle"; // depends on the common bundle!!!
import { sayHello } from "./commonDep";
export function bundle2Function() {
sayHello("from bundle2");
}
commonDep.ts :
export function sayHello(name: string) {
console.log("Hello " + name);
}
I have a Rails 6 application and using Webpacker for assets.
I have the following code in file app/javascript/packs/application.js :
export var Greeter = {
hello: function() {
console.log('hello');
}
}
And I have the following script in one of my view (HTML) file:
<script>
$(document).ready(function(){
Greeter.hello();
});
</script>
Note: I am using JQuery and it is working fine.
I am getting the following error:
Uncaught ReferenceError: Greeter is not defined.
How can we use libraryTarget and library to expose the bundled modules, so that it can be accessed from HTML files as well ?
Or, is there any other way of doing it using Rails Webpacker ?
Any help would be much appreciated!
To do this without directly mutating the window object in your application code, you'll want to export Greeter as a named export from your application.js pack and extend the Webpack config output to designate the library name and target var (or window will also work).
// config/webpack/environment.js
environment.config.merge({
output: {
library: ['Packs', '[name]'], // exports to "Packs.application" from application pack
libraryTarget: 'var',
}
})
// app/javascript/packs/application.js
export {
Greeter
}
<script>
$(document).ready(function(){
Packs.application.Greeter.hello();
});
</script>
The library name is arbitrary. Using the [name] placeholder is optional but allows you to export to separate modules if you're using multiple "packs".
As I cannot comment rossta's answer, here is what I had to do. My default config was:
// config/webpack/environment.js
const { environment } = require('#rails/webpacker')
module.exports = environment
and I just had to add the additionnal config in it:
// config/webpack/environment.js
const { environment } = require('#rails/webpacker')
environment.config.merge({
output: {
library: ['Packs', '[name]'], // exports to "Packs.application" from application pack
libraryTarget: 'var',
}
})
module.exports = environment
After that, as mentioned by rossta, each symbol which is exported in app/javascript/packs/application.js can be accessed from the DOM as Packs.application.<symbol>.
in app/javascript/packs/application.js:
import Greeter from '../greeter.js'
Greeter.hello()
and in app/javascript/greeter.js:
export default {
hello : function(){
console.log('hello')
}
}
I could fix the issue exposing Greeter object to window as follows:
export var Greeter = {
hello: function() {
console.log('hello');
}
}
window.Greeter = Greeter;
However, I am still looking for a Webpack way of accomplishing this.
I'm using React on Rails and have been trying to use Antd UI framework.
I have successully imported components from 'antd' like buttons and Datepickers
import { Button } from 'antd';
but they are not styled at all. Looking at my server I have the following error...
ERROR in ./node_modules/antd/lib/button/style/index.less
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #import "../../style/themes/default";
| #import "../../style/mixins/index";
| #import "./mixin";
# ./node_modules/antd/lib/button/style/index.js 5:0-23
# ./app/javascript/packs/application.js
ERROR in ./node_modules/antd/lib/style/index.less
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #import "./themes/default";
| #import "./core/index";
|
I have tried a few different ways to access the styles like directly references the specific stylesheet in my jsx file
//app/javascript/bundles/Page/components/Page.jsx
import React, { Component } from "react";
// import { Button, DatePicker } from 'antd'
import { Button } from 'antd';
// import Button from 'antd/lib/button';
// import 'antd/lib/button/style/css';
export default class Page extends Component {
render() {
return (
<div >
<Button type="primary">Primary</Button>
<Button>Default</Button>
<Button type="dashed">Dashed</Button>
<Button type="danger">Danger</Button>
</div>
);
}
}
Looking at the Antd docs, I have followed the Importing on demand technique and added
"import", {
"libraryName": "antd",
"style": "css",
}
]
to my .babelrc file
https://ant.design/docs/react/getting-started#Import-on-Demand
I have also tried to install the less and less-loader as I'm pretty sure it has something to do with a css file containing an '#' which indicates to me that it is a less or sass file.
The only successful way I've been able to load the styles is by putting
#import 'antd/dist/antd.css';
in my app/assets/stylesheets/page.scss.
While this option works, it does not allow for the ability to import on demand and feels like the incorrect way to import the css as it uses the rails asset pipeline instead of webpack ( via webpacker)
For me the issue was that I needed to have differently configured .less loaders in webpack for both the .less files found in antd's modules & the .less files I had written locally in my project.
For Antd I have this (Note that it's excluding /src/):
{
test: /\.(less)$/,
exclude: [
/\.(css)$/,
/src/
],
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader"
},
{
loader: "less-loader",
options: {
javascriptEnabled: true,
modifyVars: get_theme()
}
}
]
},
And for my own .less files I have this:
{
test: /\.(less)$/,
exclude: [
/\.(css)$/,
/node_modules/
],
use: [{
loader: 'style-loader' // creates style nodes from JS strings
}, {
loader: 'css-loader' // translates CSS into CommonJS
}, {
loader: "less-loader",
options: {
javascriptEnabled: true
}
}]
},
Versions of dependencies for this that I was using:
"css-loader": "^3.3.2",
"less": "3.10.3",
"less-loader": "^5.0.0",
"mini-css-extract-plugin": "^0.8.0",
"style-loader": "^1.2.1",
"antd": "4.4.2",
"webpack": "^4.43.0",
Our site is an existing MVC site and we are working on adding and replacing some parts with angular 2 components. We do not have a full angular 2 app to launch, so we are just using bootstrap to launch our components on the pages we want them.
I updated my package.json dependencies from "2.0.0-rc.1" to "~2.2.0" and now have the latest angular 2 files. I can no longer use import { bootstrap } from '#angular/platform-browser-dynamic' and launch my component with: bootstrap(MyCountComponent, [HTTP_PROVIDERS, MyService]);.
Searching it seems to have been updated to import { platformBrowserDynamic } from '#angular/platform-browser-dynamic'; and now I should launch with: platformBrowserDynamic().bootstrapModule(MyCountComponent, [HTTP_PROVIDERS, MyService]);
When I do this I'm getting the browser Console error:
Unhandled Promise rejection: (SystemJS) No NgModule metadata found for 'MyCountComponent'.
Error: No NgModule metadata found for 'MyCountComponent'...
Do I need to convert my components to modules now or is there a new way to bootstrap launch the components without a module?
Here is a code sample.
//mycount.ts
import { MyService } from '../../services/my.service';
import { HTTP_PROVIDERS } from '#angular/http';
import { bootstrap } from '#angular/platform-browser-dynamic'
import { MyCountComponent } from './mycount.component';
bootstrap(MyCountComponent, [HTTP_PROVIDERS, MyService]);
//mycount.component.ts
import { Component } from '#angular/core';
import { NgControl } from '#angular/forms';
import { MyService } from '../../services/my.service';
#Component({
selector: 'mycount',
templateUrl: './app/components/mycount/mycount.component.html'
})
export class MyCountComponent {
constructor(private _myService: MyService) {
}
get mycount() {
return this._myService.mycount;
}
}
//systemjs.config.js
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
'#angular/upgrade': 'npm:#angular/upgrade/bundles/upgrade.umd.js',
'#angular/upgrade/static': 'npm:#angular/upgrade/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
EDIT
If I have:
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule
],
bootstrap: [MyCountComponent, MyListComponent, MyDetailsComponent],
declarations: [MyCountComponent, MyListComponent, MyDetailsComponent],
exports: [MyCountComponent, MyListComponent, MyDetailsComponent],
providers: [MyService]
})
Is it possible for my page to only load 1 or 2 of the components?
I tried calling it with:
platformBrowserDynamic().bootstrapModule(MyModule, [HttpModule, MyListComponent]);
but I get an error message for any component tags missing from the page.
you need to create main #NgModule where you can import all Services, Components, Directives etc. using #NgModule you can tell your app that which component should bootstrap.
here is official links to understand that #ngModule please go through this: https://angular.io/docs/ts/latest/guide/ngmodule.html
Tips: please use Angular-cli which will create a basic structure of app just in few minutes. using Angular-cli you no need to create structued app or basic setup it will do it for you.
According to Swagger 2.0 specs, it might be possible to do this. I am referencing PathObject using $ref which points to another file. We used to be able to do this nicely using Swagger 1.2. But Swagger-UI does not seem to be able to read the referred PathObject in another file.
Is this part of spec too new and is not yet supported? Is there a way to split each "path"'s documentation into another file?
{
"swagger": "2.0",
"basePath": "/rest/json",
"schemes": [
"http",
"https"
],
"info": {
"title": "REST APIs",
"description": "desc",
"version": "1.0"
},
"paths": {
"/time": {
"$ref": "anotherfile.json"
}
}
}
To support multiple files, your libraries have to support dereferencing the $ref field. But I would not recommend to deliver the swagger file with unresolved references. Our swagger defintion has around 30-40 files. Delivering them via HTTP/1.1 could slow down any reading application.
Since we are building javascript libs, too, we already had a nodejs based build system using gulp. For the node package manager (npm) you can find some libraries supporting dereferencing to build one big swagger file.
Our base file looks like this (shortened):
swagger: '2.0'
info:
version: 2.0.0
title: App
description: Example
basePath: /api/2
paths:
$ref: "routes.json"
definitions:
example:
$ref: "schema/example.json"
The routes.json is generated from our routing file. For this we use a gulp target implementing swagger-jsdoc like this:
var gulp = require('gulp');
var fs = require('fs');
var gutil = require('gulp-util');
var swaggerJSDoc = require('swagger-jsdoc');
gulp.task('routes-swagger', [], function (done) {
var options = {
swaggerDefinition: {
info: {
title: 'Routes only, do not use, only for reference',
version: '1.0.0',
},
},
apis: ['./routing.php'], // Path to the API docs
};
var swaggerSpec = swaggerJSDoc(options);
fs.writeFile('public/doc/routes.json', JSON.stringify(swaggerSpec.paths, null, "\t"), function (error) {
if (error) {
gutil.log(gutil.colors.red(error));
} else {
gutil.log(gutil.colors.green("Succesfully generated routes include."));
done();
}
});
});
And for generating the swagger file, we use a build task implementing SwaggerParser like this:
var gulp = require('gulp');
var bootprint = require('bootprint');
var bootprintSwagger = require('bootprint-swagger');
var SwaggerParser = require('swagger-parser');
var gutil = require('gulp-util');
var fs = require('fs');
gulp.task('swagger', ['routes-swagger'], function () {
SwaggerParser.bundle('public/doc/swagger.yaml', {
"cache": {
"fs": false
}
})
.then(function(api) {
fs.writeFile('public/doc/swagger.json', JSON.stringify(api, null, "\t"), function (error) {
if (error) {
gutil.log(gutil.colors.red(error));
} else {
gutil.log("Bundled API %s, Version: %s", gutil.colors.magenta(api.info.title), api.info.version);
}
});
})
.catch(function(err) {
gutil.log(gutil.colors.red.bold(err));
});
});
With this implementation we can maintain a rather large swagger specification and we are not restricted to special programming language or framework implementation, since we define the paths in the comments to the real routing definitions. (Note: The gulp tasks are split in multiple files too.)
While it would theoretically be possible to do that in the future, the solution is still not fully baked into the supporting tools so for now I'd highly recommend keeping it in one file.
If you're looking for a way to manage and navigate the Swagger definition, I'd recommend using the YAML format of the spec, where you can add comments and that may ease up navigation and splitting of a large definition.
You can also use JSON Refs library to resolve such multi-file Swagger spec.
I've written about it in this blog post
There is also this GitHub repo to demonstrate how all of this work.
My solution to this problem is using this package below to solve the reference issue
https://www.npmjs.com/package/json-schema-ref-parser
Here is the code snippet when generating the swagger UI using that library. I was using Express.js for my node server.
import express from 'express';
import * as path from 'path';
import refParser from '#apidevtools/json-schema-ref-parser';
import swaggerUi from 'swagger-ui-express';
const port = 3100;
const app = express();
app.get('/', async (req, res) => {
res.redirect('/api-docs')
});
app.use(
'/api-docs',
async function (req: express.Request, res: express.Response, next: express.NextFunction) {
const schemaFilePath = path.join(__dirname, 'schema', 'openapi.yml');
try {
// Resolve $ref in schema
const swaggerDocument = await refParser.dereference(schemaFilePath);
(req as any).swaggerDoc = swaggerDocument;
next();
} catch (err) {
console.error(err);
next(err);
}
},
swaggerUi.serve,
swaggerUi.setup()
);
app.listen(port, () => console.log(`Local web server listening on port ${port}!`));
Take a look at my Github repository to see how it works