using d3.js as an external in webpack - d3.js

I'm using this tutorial to setup a React.js project with webpack. The webpack.config.js below is almost an exact copy (except that I'm using an app and 'dist' folder), and I am also adding d3.js as an external. Because React is added as an external it lets me do require('react') in any of my app files without including it in the bundle. I wish to do the same with d3.js and have installed it as a node_module, and listed it in the externals area of my webpack config, but when I do require('d3') i get an error message that it's not available.
How can I use d3 (or jQuery for that matter) as an external if I have it installed as a node_module?
this is my project setup
/app
/dist
/node_modules
package.json
webpack.config.js
module.exports = {
entry: './app/index.jsx',
output: {
path: './dist',
filename: 'bundle.js', //this is the default name, so you can skip it
//at this directory our bundle file will be available
//make sure port 8090 is used when launching webpack-dev-server
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
}
]
},
externals: {
//don't bundle the 'react' npm package with our bundle.js
//but get it from a global 'React' variable
'react': 'React',
'd3': 'd3'
},
resolve: {
modulesDirectories: ['app', 'node_modules'],
extensions: ['', '.js', '.jsx']
}
}

I know this question has been open a while, but hopefully this answer is still useful!
If you have installed d3 (or jQuery) as a node_module, you can use the webpack ProvidePlugin to tie an arbitrary key to a module.
The key will be then be available to require anywhere in your webpack app.
E.g. webpack.config.js
{
...lots of webpack config here...
...
plugins: [
new webpack.ProvidePlugin({
d3: 'd3',
$: 'jquery'
})
]
...
}
Then in my-file.js
var d3 = require('d3')
Hope that helps!

Related

Getting svelte-material-ui working with snowpack and sass

I'm trying to get svelte material UI working with snowpack.
I have installed Snowpack and Snowpacks svelte template like so:
npm install --save-dev snowpack#next
npx create-snowpack-app xpapp --template #snowpack/app-template-svelte
This works, the sample svelte page shows up. Next I followed the Svelte Material UI instructions to "bundle this in your own code" as cited on the Usage chapter in the instructions here: https://github.com/hperrin/svelte-material-ui#usage
So I installed Sass and configured it in my snowpack.config.json file like this:
{
"extends": "#snowpack/app-scripts-svelte",
"scripts": {
"build:scss": "sass"
},
"devOptions": {},
"installOptions": {}
}
I followed the (very concise) instructions here: https://www.snowpack.dev/#sass
I've also added an empty src/theme/_smui-theme.scss file to my source files as the instructions say, and I installed the nessecary #smui components.
The problem is that I'm currently getting this error when starting the snowpack dev server:
> snowpack dev
Snowpack Dev Server (Beta)
NOTE: Still experimental, default behavior may change.
Starting up...
⠙ snowpack installing... #smui/icon-button, #smui/top-app-bar, svelte/internal
✘ /home/erik/Projects/svelte-xpapp/xpapp/node_modules/#smui/icon-button/_index.scss
Error: Unexpected character '#' (Note that you need plugins to import files that are not JavaScript)
at error (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:161:30)
at Module.error (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:15120:16)
at tryParse (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:15009:23)
at Module.setSource (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:15410:30)
at ModuleLoader.addModuleSource (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:17460:20)
at async ModuleLoader.fetchModule (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:17521:9)
at async /home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:17491:36
at async Promise.all (index 0)
at async ModuleLoader.fetchModule (/home/erik/Projects/svelte-xpapp/xpapp/node_modules/snowpack/node_modules/rollup/dist/shared/rollup.js:17522:9)
at async Promise.all (index 0)
It seems that the #import statements in Material UI's _index.scss aren't recognized. I figure Snowpack should interpret/transpile .scss files, but it doesn't seem to be doing that.
So I came across the same problem using Svite as well as Snowpack. I was able to use the bare implementation:
// component.svelte <script>
import Button, { Label } from '#smui/button/bare'
import '#smui/button/bare.css'
That's all that's required with Svite.
With Snowpack, I needed to add rollup-plugin-svelte and update snowpack.config.js
// snowpack.config.js
module.exports = {
// ...
installOptions: {
rollup: { plugins: [require('rollup-plugin-svelte')()] }
},
// ...
}
I got it working with these install options:
installOptions: {
rollup: {
plugins: [
require("rollup-plugin-svelte")({
include: ["./node_modules"],
}),
require("rollup-plugin-postcss")({
use: [
[
"sass",
{
includePaths: ["./src/theme", "./node_modules"],
},
],
],
}),
],
},
},
Unfortunately, you'll have to run npx snowpack dev --reload for changes to the theme to take effect.
This won't extract css into .css files.
I also got an error message with the Dialog component during a production build.
Here is a full example: https://github.com/LeanderG/svelte-smui

Gatsby Develop Failing using gatsby-plugin-sass

After installing the gatsby-plugin-sass module:
When I try to run gatsby build, I get the following error:
ERROR
Unknown error from PostCSS plugin. Your current PostCSS version is 6.0.23, but autoprefixer uses 7.0.26. Perhaps this is the source of the error below.
ERROR #98123 WEBPACK
Generating development JavaScript bundle failed
Browser queries must be an array or string. Got object.
File: src/indexs.sass
failed Building development bundle - 9.200s
I have been working on a resolution to this for hours. I have tried:
custom webpack rules in gatsby-node.js for sass files
reading, re-reading, and re-re-reading the instruction on gatsby's site
updating PostCSS using npm in every way I know how
So far, nothing has worked.
Why is it so complicated to get sass working with gatsby? When the documentation on gatsby's site makes it seem so easy?
Any suggestions what I can do to get this working?
in gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
// console.log('rules',rules)
// console.log('rules.css',rules.css())
// console.log('rules',rules.postcss())
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
})
}
In gatsby-config.js:
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [require(`postcss-preset-env`)({ stage: 0 })],
},
},
`gatsby-plugin-sass`,
the sass import line in gatsby-browser.js:
import "./src/indexs.sass"
Using sass instead of node-sass saved my day.
remove node-sass
npm uninstall node-sass
or
yarn remove node-sass
and add sass aka dart-sass
npm install --save-dev sass
or
yarn add sass
then edit gatsby-config.js
plugins: [
{
resolve: `gatsby-plugin-sass`,
options: {
implementation: require("sass"),
},
},
]
now run gatsby develop
:)
I'm a bit late to the party but hopefully this might help someone.
I have Sass setup and working with Gatsby without to much extra config required.
Install both node-sass and gatsby-plugin-sass via npm.
npm install --save node-sass gatsby-plugin-sass
Include gatsby-plugin-sass in your gatsby-config.js file in plugins: [] as below with any other Gatsby plugins you maybe using.
module.exports = {
siteMetadata: {
title: `#`,
description: `#`,
author: `#`,
},
plugins: [
`gatsby-plugin-sass`,
],
}
Write your styles as .sass or .scss files and import your main styles.scss (or whatever you prefer to name it) either in your main Layout.js file or gatsby-browser.js file as below using the path to the location of your styles.scss file.
import "./src/styles/styles.scss"
I hope this works for you but if you have any other trouble add a comment and I'll try to reply back.
I hope someone chimes in on this to show how exactly to set up gatsbys sass plugin. I could not get it to work at all.
But I did find a workaround in my case:
I removed gatsby-plugin-sass from the plugins array in gatsby-config.js, turning it off (but I did not uninstall it using npm)
I installed postcss-node-sass and postcss
I added this info to the plugins array in gatsby-config.js:
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [
require(`postcss-preset-env`)({ stage: 0 }),
require(`postcss-node-sass`)(),
],
},
},
I added a custom rule for webpack in gatsby-node.js:
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions,
}) => {
// console.log('rules',rules)
// console.log('rules.css',rules.css())
// console.log('rules',rules.postcss())
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
})
}

Custom webpack configuration

I'm using Laravel 5.6 and I would like to add the vtk.js dependency.
I'm using the basic configuration of webpack included by laravel-mix. I'm creating my default app.js and don't want to change this behaviour. So vtk should be included in the app.js.
I also saw that we can add a custom webpack config like this
mix.webpackConfig({
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
]
}
});
But I realy don't know how to include the module.exports and module from the webpack of js in the mix of laravel...
You have to append the path your js file in your webpack
run npm dev
const path = require('path');
const webpack = require('webpack');
const vtkRules = require('vtk.js/Utilities/config/dependency.js').webpack.v2.rules;
mix.webpackConfig({
module: {
rules: [...vtkRules]
},
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
]
}
});
I'm not used to VTK, you have to import/configure everything else on your app.js, which is your entrypoint.

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);

Getting Babel 6 to work with IE8 (via. Gulp/Webpack)

I've got Babel 6 working nicely with Gulp and Webpack. I now need to polyfill it to get IE8 support.
I've installed the babel-polyfill, but can't get it working and the docs and Google haven't helped so far.
My Gulp task (inc. Webpack config):
gulp.task('webpack', function(callback) {
var webpackConfig = {
context: __dirname + '../../../js',
entry: {
homepage: [
'babel-polyfill',
'./public/homepage/homepage.js'
]
},
output: {
path: __dirname + '../../../dist/public/scripts/',
filename: '[name].bundle.js'
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/, // Only run .js files through Babel
include: /js/, // Only include the /js dir
query: {
//plugins: ['transform-runtime'], // Disabled pending fix to https://github.com/babel/babel/issues/2954
presets: ['es2015'],//, 'stage-0'
}
}
]
}
};
webpack(webpackConfig, function(err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
gutil.log('[webpack]', stats.toString({
// output options
}));
callback();
});
});
From the docs (https://babeljs.io/docs/usage/polyfill/):
Usage in Node / Browserify / Webpack
To include the polyfill you need to require it at the top of the entry point to > your application.
require("babel-polyfill");
Usage in Browser
Available from the dist/polyfill.js file within a babel-polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a before it.
NOTE: Do not require this via browserify etc, use babel-polyfill.
I've tried simply adding the polyfill.js file to the top of the page, but IE8 still isn't happy with the compiled code's use of the default keyword.
I've also tried adding the polyfill to the webpack process, as per http://jamesknelson.com/using-es6-in-the-browser-with-babel-6-and-webpack/ and other suggestions from Google
What am I doing wrong?

Resources