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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With