在Webpack中使用d3.js作为外部 [英] using d3.js as an external in webpack
问题描述
我正在使用本教程来设置React.js webpack项目.下面的webpack.config.js几乎是一个精确的副本(除了我使用的是app
和'dist'文件夹),而且我还将d3.js添加为external
.由于React是作为external
添加的,因此它使我可以在任何应用程序文件中执行require('react')
而不将其包含在捆绑包中.我希望对d3.js
做同样的事情,并将其安装为node_module,并将其列出在我的webpack配置的外部区域中,但是当我执行require('d3')
时,我收到一条错误消息,提示它不可用.
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.
如果我将d3
(或jQuery)安装为node_module,如何将其用作外部?
How can I use d3
(or jQuery for that matter) as an external if I have it installed as a node_module?
这是我的项目设置
/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!
如果您已将d3(或jQuery)安装为node_module,则可以使用webpack ProvidePlugin将任意键绑定到模块.
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.
然后该密钥将可用于在webpack应用中的任何地方.
The key will be then be available to require anywhere in your webpack app.
例如 webpack.config.js
{
...lots of webpack config here...
...
plugins: [
new webpack.ProvidePlugin({
d3: 'd3',
$: 'jquery'
})
]
...
}
然后在 my-file.js
var d3 = require('d3')
希望有帮助!
这篇关于在Webpack中使用d3.js作为外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!