【问题标题】:using d3.js as an external in webpack在 webpack 中使用 d3.js 作为外部
【发布时间】:2015-10-13 05:38:59
【问题描述】:

我正在使用this tutorial 使用 webpack 设置 React.js 项目。下面的 webpack.config.js 几乎是一个精确的副本(除了我使用的是 app 和 'dist' 文件夹),我还将 d3.js 添加为 external。因为 React 是作为 external 添加的,所以我可以在我的任何应用程序文件中执行 require('react') ,而无需将其包含在包中。我希望对d3.js 执行相同的操作,并将其安装为 node_module,并将其列在我的 webpack 配置的外部区域中,但是当我执行 require('d3') 时,我收到一条错误消息,指出它不可用。

如果我将 d3(或 jQuery)作为 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']
    }
}

【问题讨论】:

    标签: d3.js webpack


    【解决方案1】:

    我知道这个问题已经开放了一段时间,但希望这个答案仍然有用!

    如果您已将 d3(或 jQuery)安装为 node_module,则可以使用 webpack ProvidePlugin 将任意键绑定到模块。

    然后,您的 webpack 应用程序中的任何地方都可以使用该密钥。

    例如webpack.config.js

    {
     ...lots of webpack config here...
     ...
     plugins: [
        new webpack.ProvidePlugin({
            d3: 'd3',
            $: 'jquery'
        })
     ]
     ...
    }
    

    然后在 my-file.js

    var d3 = require('d3')

    希望有帮助!

    【讨论】:

    猜你喜欢
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2018-06-13
    相关资源
    最近更新 更多