How to bundle d3 v4 using webpack - d3.js

I was using D3 v3 with webpack which was simple with one single package. Now that D3 v4 has become modular with separate packages, I am unable to bundle them into single package.
I have referred to mbostock's article below using rollup but it fails saying it is unable to load d3 from index.js. Can anyone help me with how to bundle them using webpack?
EDIT 1:
I removed d3 from the rollup options and the rollup worked fine. I have explained the steps below
D3 v4 installed.
Added rollup config and storing to ./dist/d3.min.js
pointed webpack to the ./dist/d3.min.js
tried resolve.alias in webpack and require("d3") in one home.js. But no luck it says
cannot resolve module d3 in home.js
tried webpack.Provideplugin in home.js. Still the above error.
Can anyone please help me with getting this d3 loaded?
Rollup.js
import node from "rollup-plugin-node-resolve";
export default {
entry: "index.js",
format: "umd",
moduleName: "d3",
plugins: [node()],
dest: "./dist/d3.js"
};
index.js
export * from "d3-selection";
export * from "d3-zoom";
export * from "d3-scale";
export * from "d3-drag";
export * from "d3-force";
export * from "d3-axis";
webpack.config.js
var webpack = require('webpack')
var path = require('path')
module.exports = {
entry: [
//"./dist/d3-combined.js",
"./client/home.js"
,"./client/pages.js"
,"./client/graph.js"
,"./client/orient_databases.js"
,"./node_modules/d3/d3.js",
,"./public/jquery-2.2.4.min.js"
]
,output: {
path: path.join(__dirname,'dist')
// ,path: '/static'
,publicPath: 'http://localhost:3000/scripts/'
,filename: 'bundle.js'
}
,plugins :[
new webpack.ProvidePlugin({
jquery : "jquery"
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
]
,module: {
// avoid webpack trying to shim process
noParse: /es6-promise\.js$/,
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
// excluding some local linked packages.
// for normal use cases only node_modules is needed.
exclude: /node_modules|vue\/dist|vue-router\/|vue-loader\/|vue-hot-reload-api\//,
loader: 'babel-loader',
query : {
presets : ['es2015']
//,optional : ["runtime"]
}
}
]
}
,resolve : {
//root : [path.resolve('./node_modules')],
alias : [ {"d3": path.join(__dirname,"dist/d3.min.js") } ],
modulesDirectories : ["node_modules"]
}
}

There are quite a few incompatibilities with D3 v4's rollup approach and webpack—yours is totally a sensible approach.
It looks like you're missing the minification step? (Rollup.js creates d3.js, but webpack.config.js expects d3.min.js)
It's also possible that webpack v2's new configuration has some relevant fixes.
This setup works for me (using webpack v2):
home.js
let d3 = require('d3');
rollup.config.js
import npm from 'rollup-plugin-node-resolve';
export default {
entry: './d3.bundle.js',
format: 'umd',
moduleName: 'd3',
plugins: [npm({jsnext: true})],
dest: './dist/d3.js'
};
d3.bundle.js
export * from "d3-selection";
export * from "d3-zoom";
export * from "d3-scale";
export * from "d3-drag";
export * from "d3-force";
export * from "d3-axis";
package.json
{
...
"scripts": {
"prepublish": "rollup -c && uglifyjs dist/d3.js -c -m -o dist/d3.min.js"
},
...
}
webpack.config.js
module.exports = {
...
resolve: {
alias: {
'd3': path.resolve(__dirname, 'dist/d3.min.js')
}
},
...
};

Related

Laravel mix webpack - Ignore locales when importing Moment.js

I would like to load 2 locales en-gb and fr-ch only from Moment.js , then assign the moment class to the scopewindow to use the library everywhere in my Vuejs components.
Currently, my app.js has this require line:
window.moment = require('moment')
I am suspecting it can be accomplished thanks to the solutions here (adding IgnorePlugin and ContextReplacementPlugin to webpack.config.js):
plugins.push(new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en-gb|fr-ch/))
module.exports.plugins = plugins;
OR
plugins.push(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/))
module.exports.plugins = plugins;
Where should you add these pieces of code (webpack.config.js and/or app.js and/or webpack.mix.js) to ignore all other locales when importing momentjs?
mix.webpackConfig({
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
})
Source: https://laracasts.com/discuss/channels/elixir/laravel-mix-prevent-momentjs-locales
mix.webpackConfig( webpack => {
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
});
this way you dont have to import webpack on the top of your file, which sometimes can cause errors.
and you also can put other necessary options like this
mix.webpackConfig( webpack => {
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
resolve: {
extensions: ['.js', '.vue'],
alias: {
'#': __dirname + '/resources',
'#root': __dirname,
'#pages': __dirname + '/resources/js/pages'
},
fallback: { "path": false },
},
});

Laravel + VueJs + Webpack + Karma = world of pain

Is it possible to write unit tests for VueJs if you are using Laravel's Elixir for your webpack configuration?
VueJs 2x has a very simple example for a component test: Vue Guide Unit testing
<template>
<span>{{ message }}</span>
</template>
<script>
export default {
data () {
return {
message: 'hello!'
}
},
created () {
this.message = 'bye!'
}
}
</script>
and then...
// Import Vue and the component being tested
import Vue from 'vue'
import MyComponent from 'path/to/MyComponent.vue'
describe('MyComponent', () => {
it('has a created hook', () => {
expect(typeof MyComponent.created).toBe('function')
})
it ...etc
})
and gives an example of a karma conf file here: https://github.com/vuejs-templates
But the Karma configuration file requires a webpack configuration file
webpack: webpackConfig,
The only problem is the Laravel's Elixir is creating the webpack configuration so it can't be included.
I have tried creating another webpack configuration file based on the example from https://github.com/vuejs-templates/webpack.
Something like this:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
and included it like...
// Karma configuration
// Generated on Wed Mar 15 2017 09:47:48 GMT-0500 (CDT)
var webpackConf = require('./karma.webpack.config.js');
delete webpackConf.entry;
module.exports = function(config) {
config.set({
webpack: webpackConf, // Pass your webpack.config.js file's content
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
But I am getting errors that seem to indicate that webpack isn't doing anything.
ERROR in ./resources/assets/js/components/test.vue
Module parse failed: /var/www/test/resources/assets/js/components/test.vue Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <template>
| <span >{{test}}</span>
| </template>
Ok, I got this to work. Couple of things that might help.
I was originally running gulp, and trying to run tests in my vagrant box, to try to match the server configuration. I think that makes it much harder to find examples and answers on the internet.
Ok, so the main problem I was having is that webpack wasn't processing my components included in my test files. I copied the webpack config out of the laravel-elixir-vue-2/index.js node module directly into the Karma configuration file and it started working.
The key is that karma-webpack plugin needs both the resolve and module loader configuration settings (resolve with alias and extensions) for it to work.
Hope this helps someone.
karma.conf.js:
module.exports = function (config) {
config.set({
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the `browsers` array below.
browsers: ['Chrome'],
frameworks: ['jasmine'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack']
},
webpack: {
resolve: {
alias: {
vue: 'vue/dist/vue.common.js'
},
extensions: ['.js', '.vue']
},
vue: {
buble: {
objectAssign: 'Object.assign'
}
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'file-loader',
query: {
limit: 10000,
name: '../img/[name].[hash:7].[ext]'
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: '../fonts/[name].[hash:7].[ext]'
}
}
]
}
},
webpackMiddleware: {
noInfo: true,
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' },
]
},
});
};
I ran into the exact same problem. The accepted answer did not fully work for me. The following solved my issue:
Install relevant loaders for webpack:
npm install --save-dev vue-loader file-loader url-loader
Create webpack config file (note the format). The accepted answer produced errors citing invalid format of the webpack.config.js file. At least with me it did.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.vue$/,
use: [
{ loader: 'vue-loader' }
]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: [
{
loader: 'file-loader',
query: {
limit: 10000,
name: '../img/[name].[hash:7].[ext]'
}
}
]
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: [
{
loader: 'url-loader',
query: {
limit: 10000,
name: '../fonts/[name].[hash:7].[ext]'
}
}
]
}
]
}
}
karma.conf.js
// Karma configuration
var webpackConf = require('./webpack.config.js');
delete webpackConf.entry
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
port: 9876, // web server port
colors: true,
logLevel: config.LOG_INFO,
reporters: ['progress'], // dots, progress
autoWatch: true, // enable / disable watching files & then run tests
browsers: ['Chrome'], //'PhantomJS', 'Firefox',
singleRun: true, // if true, Karma captures browsers, runs the tests and exits
concurrency: Infinity, // how many browser should be started simultaneous
webpack: webpackConf, // Pass your webpack.config.js file's content
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
/**
* base path that will be used to resolve all patterns (eg. files, exclude)
* This should be your JS Folder where all source javascript
* files are located.
*/
basePath: './resources/assets/js/',
/**
* list of files / patterns to load in the browser
* The pattern just says load all files within a
* tests directory including subdirectories
**/
files: [
{pattern: 'tests/*.js', watched: false},
{pattern: 'tests/**/*.js', watched: false}
],
// list of files to exclude
exclude: [
],
/**
* pre-process matching files before serving them to the browser
* Add your App entry point as well as your Tests files which should be
* stored under the tests directory in your basePath also this expects
* you to save your tests with a .spec.js file extension. This assumes we
* are writing in ES6 and would run our file through babel before webpack.
*/
preprocessors: {
'app.js': ['webpack', 'babel'],
'tests/**/*.spec.js': ['babel', 'webpack']
},
})
}
Then run karma start and everything should work.

Webpack 1.x Hot Module Replacement Modules not updating

I'm trying to integrate Angular 2 with HMR in Visual Studio 2015. I have 2 projects with the same file contents and same directory structure and both uses HMR with Angular 2. But the HMR for each project looks for different to update the bundle. i.e. For App1, it looks for Typescript files (And JS are not generated for them in VS) like:
Having Module A depends upon B, and B Upon C. If C is updated, the whole bundle gets updated that works good.
But in App2, it looks for 1 Typescript file main.ts and 2 Javascript files, like:
If C is updated, the module don't get updated, unless I explicitly modify C's Javascript file (Generated by VS on build)!
How do I tell Webpack HMR to look for these Typescript files and update the bundle if I changed any of them.
My webpack.config.js are same for both projects like:
var path = require('path');
var webpack = require('webpack');
module.exports = {
resolve: { extensions: [ '', '.js', '.ts' ] },
entry: { 'main-client': './ClientApp/main.ts' },
output: {
filename: '[name].js',
path: path.join(__dirname, './wwwroot/dist'),
publicPath: '/dist/'
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts' },
{ test: /\.html$/, loader: 'raw' }
]
}
};
I had the same problem and fixed it by enabling HMR in main.ts.
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { enableProdMode } from '#angular/core';
import { AppModule } from './app/app.module';
// Enables Hot Module Replacement.
declare var module: any;
if (module.hot) {
module.hot.accept();
}
platformBrowserDynamic().bootstrapModule(AppModule);

Error when combining sass-loader with css-modules

I'm getting the following error when using SASS's map-get.
ERROR in ./src/special.scss
Module build failed: ModuleBuildError: Module build failed: Unknown word (11:14)
9 |
10 | #mixin mediaquery($name) {
> 11 | #media #{map-get($breakpoints, $name)} {
| ^
12 | #content;
13 | }
14 | }
This is only happening when I use both the sass-loader and another loader.
I first thought this was caused by the PostCSS Loader, but it seems like it's the sass-loading causing problems and not transforming the scss when using css-modules.
I've created a sample repo illustrating the problem: https://github.com/tiemevanveen/sass-css-components-fail-example.
You can use the different branches to test:
master: CSS Modules + SASS
postcss CSS Modules + SASS + PostCSS
log-source: Uses CSS modules + SASS + Custom source logging module
no-css-modules: SASS + Custom source logging module
Only the first and the last branch run without errors.
I've created the log-source example to see what the sass-loader is returning and it looks like it's not transforming the sass (but this might also be me misinterpreting how the loaders work).
The other example without css modules does show the right transformed code..
I'm puzzled why the master branch (without postcss or another custom loader) is working fine though.. if something would be wrong with the sass-loader then that one should also fail right?
I've filed an issue, but I'm thinking this has more chance on StackOverflow since it's such a specific problem and might be more a config problem. Here's my webpack config:
const webpack = require('webpack');
const path = require('path');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WriteFilePlugin = require('write-file-webpack-plugin');
module.exports = {
devtool: 'source-source-map',
debug: true,
context: path.resolve(__dirname, './src'),
entry: {
app: './index.js'
},
output: {
path: path.resolve(__dirname, './static'),
filename: '[name].js',
publicPath: '/static/'
},
devServer: {
outputPath: path.resolve(__dirname, './static'),
},
plugins: [
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('[name].css'),
new WriteFilePlugin()
],
module: {
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', [
'css?modules&importLoaders=1&localIdentName=[path]_[name]_[local]',
// 'postcss-loader',
'sass'
])
},
// + js loader
]
},
postcss: [
autoprefixer({ browsers: ['> 0.5%'] })
],
resolveLoader: {
fallback: [
path.resolve(__dirname, 'loaders'),
path.join(process.cwd(), 'node_modules')
]
},
resolve: {
extensions: ['', '.js', '.json'],
}
};
You need to increase the importLoaders query parameter as you add loaders. That feature is poorly documented and confusing, but in your samples repo, importLoaders=2 with both Sass and PostCSS works.

Integrating D3 with Angular-cli

I am trying to integrate D3 chart library with Angular CLI. First I installed d3 with npm install d3 --save. Once done my node_modules looks like
d3 version is "d3": "^4.2.2".
Then I set up configuration as below.
angular-cli-build.js
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
......
'd3/**/*'
]
});
};
system-config.ts
"use strict";
// SystemJS configuration file, see links for more information
// https://github.com/systemjs/systemjs
// https://github.com/systemjs/systemjs/blob/master/docs/config-api.md
/***********************************************************************************************
* User Configuration.
**********************************************************************************************/
/** Map relative paths to URLs. */
const map:any = {
'#angular2-material': 'vendor/#angular2-material',
// 'd3': 'vendor/d3'
'd3': 'vendor/d3/build'
};
/** User packages configuration. */
const materialPackages:string[] = [
'core',
'button',
'icon',
'sidenav',
'toolbar',
'list',
'card'
];
const packages:any = {
'd3': {
format: 'cjs',
defaultExtension: 'js',
main: 'd3'
},
};
materialPackages.forEach(name => {
packages[`#angular2-material/${name}`] = {
format: 'cjs',
defaultExtension: 'js',
main: name
};
});
////////////////////////////////////////////////////////////////////////////////////////////////
/***********************************************************************************************
* Everything underneath this line is managed by the CLI.
**********************************************************************************************/
const barrels:string[] = [
// Angular specific barrels.
'#angular/core',
'#angular/common',
'#angular/compiler',
'#angular/forms',
'#angular/http',
'#angular/router',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
// Thirdparty barrels.
'rxjs',
// App specific barrels.
'app',
'app/shared',
'app/bar',
'app/chart',
/** #cli-barrel */
];
const cliSystemConfigPackages:any = {};
barrels.forEach((barrelName:string) => {
cliSystemConfigPackages[barrelName] = {main: 'index'};
});
/** Type declaration for ambient System. */
declare var System:any;
// Apply the CLI SystemJS configuration.
System.config({
map: {
'#angular': 'vendor/#angular',
'rxjs': 'vendor/rxjs',
'main': 'main.js',
},
packages: cliSystemConfigPackages
});
// Apply the user's configuration.
System.config({map, packages});
In app.module.ts, I imported d3 as below.
import * as d3 from 'd3';
Then,
#NgModule({
declarations: [AppComponent, d3],
providers: [],
imports: [],
bootstrap: [AppComponent],
})
Following is what my dist folder looks,
When I try to build the project with ng build it gives below error.
Cannot find module 'd3'
Any suggestions are highly appreciated.
Thank You
You should try to add d3 typings to your project, d3 does not include typings and you have to get it to use the import system.
You can :
use the TypeScript Definition Manager in order to import the requested typing in your project :
typings install dt~d3 --global --save
Then you will have the definition file for d3 in your typings directory.
Refers to angular-cli, you can install typings by using npm :
npm install #types/d3 --save-dev
After all, you should take a look to the d3 definition file to be sure that is the correct typing for the latest release of d3.

Resources