webpack externals设置无法正常工作,包含文件

时间:2017-01-30 07:48:48

标签: javascript webpack

我正在为react-toolbox重新打包cljsjs,我需要做的事情是 not 在完成的包中包含react和react-dom,所以,我很明显加入:

externals: {
    "react": "React",
    "react-dom": "ReactDOM"
},

到webpack.config.js,但它似乎没有工作。在生成的.js文件中,我期望类似:

123: function(...) {
    module.exports = React;
},

但是找到了:

/* 372 */
/***/ function(module, exports, __webpack_require__) {

    /* WEBPACK VAR INJECTION */(function(process) {/**
     * Copyright 2013-present, Facebook, Inc.
     * All rights reserved.
     *
     * This source code is licensed under the BSD-style license found in the
     * LICENSE file in the root directory of this source tree. An additional grant
     * of patent rights can be found in the PATENTS file in the same directory.
     *
     */

    'use strict';

    var _assign = __webpack_require__(371);

    var ReactChildren = __webpack_require__(373);
    var ReactComponent = __webpack_require__(386);

当使用库时,React初始化两次:

enter image description here

任何想法为什么?

我的完整webpack.config如下所示:

const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
process.env.NODE_ENV = "production";

var entryName = "react-toolbox.inc";

module.exports = {
    entry: path.join(__dirname, "components", "index.js"),

    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    },

    output: {
        filename: entryName + ".js",
        libraryTarget: "var",
        library: "ReactToolbox"
    },

    resolve: {
        extensions: ['', '.js', '.jsx', '.scss']
    },

    module: {
        loaders: [
            {
                test: /(\.js|\.jsx)$/,
                exclude: /(node_modules)/,
                loader: "babel",
                query: {
                    presets: ['es2015', 'react', 'stage-0'],
                    plugins: ['add-module-exports']
                }
            },
            {
                test: /(\.scss|\.css)$/,
                loader: ExtractTextPlugin.extract('style', 'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss')
            }
        ]
    },

    postcss: [autoprefixer],

    plugins: [
        new ExtractTextPlugin(entryName + '.css', {allChunks: true})
    ]
};

,生成的文件为:https://gist.githubusercontent.com/pupeno/9b58dd86608378966e950500456286e8/raw/63cd63ad2eca50201ca622d6e7e759d473eeb011/react-toolbox.inc.js

图书馆需要以这些方式进行反应:

import React, { PropTypes } from 'react';
import React, { Component, PropTypes } from 'react';
import React from 'react';
import ReactDOM from 'react-dom';
import React, { cloneElement, Component, PropTypes } from 'react';

我正在使用webpack 1.14。

我也尝试过:

externals: {
  "react": true,
  "react-dom": true
}

externals: {
  "react": "commonjs2",
  "react-dom": "commonjs2"
}

2 个答案:

答案 0 :(得分:0)

我试过了:

/* main.js */
import React from 'react';

export default () => <div>Hello World!</div>

/* webpack.config.js */
module.exports = [
    {
        entry: `${__dirname}/main.js`,
        output: {
            filename: 'bundle.js',
            path: `${__dirname}`,
            library: 'Foobar',
            libraryTarget: 'var'
        },
        externals: {
            'react': 'React',
            'react-dom': 'ReactDOM'
        },
        module: {
            loaders: [
                {
                    test: /\.jsx?$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader',
                    query: {
                        presets: [
                            'es2015',
                            'react',
                            'stage-0'
                        ],
                        plugins: [
                            'add-module-exports'
                        ]
                    }
                }
            ]
        }
    }
];

/* bundle.js (compiled) */
var Foobar =
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};

/******/    // The require function
/******/    function __webpack_require__(moduleId) {

/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;

/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };

/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/        // Flag the module as loaded
/******/        module.loaded = true;

/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }


/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;

/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;

/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";

/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

    'use strict';

    Object.defineProperty(exports, "__esModule", {
      value: true
    });

    var _react = __webpack_require__(1);

    var _react2 = _interopRequireDefault(_react);

    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

    exports.default = function () {
      return _react2.default.createElement(
        'div',
        null,
        'Hello World!'
      );
    };

    module.exports = exports['default'];

/***/ },
/* 1 */
/***/ function(module, exports) {

    module.exports = React;

/***/ }
/******/ ]);

唯一的区别是,我删除了css部分。 你可以试试那个配置(当然还有你的文件名和路径)?

另一种替代方式:

不要在脚本中导入它们并将它们作为全局模块添加到您的linter中。

答案 1 :(得分:0)

npm i -D webpack-node-externals
var nodeExternals = require('webpack-node-externals');
    module.exports = {
    target: 'node', // important in order not to bundle built-in modules like path, fs, etc.
    externals: [nodeExternals({
        // this WILL include this libraries in the bundle
        allowlist: ['jquery', 'moment', 'eonasdan-bootstrap-datetimepicker']
    })]
}