简体   繁体   中英

Failure to bundle a React component library via Webpack, but it works via Babel

Similarly as described in this article , I'm writing a library of React components ("my-react-components"). These components are to be used in several client applications, one of them being named "my-app".

I started by declaring a component in my-react-components/src/index.js :

import React from 'react';

const MyComponent = () => (
  <h1>Hello from My Component</h1>
);

export default MyComponent;

As suggested in the article, I started by building the NPM package via Babel (in my package.json I added a script: "transpile": "babel src/index.js -o dist/main.js" . The code generated in my-react-components/dist/main.js looks like this:

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireDefault(require("react"));

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

var MyComponent = function MyComponent() {
  return /*#__PURE__*/_react["default"].createElement("h1", null, "Hello from My Component");
};

var _default = MyComponent;
exports["default"] = _default;

Then:

  • I published the library to the NPM repo
  • I added the my-react-components dependency in my-app/package.json
  • I imported it in a React view: my-app/LoginContainer.js
import React, { Component } from 'react';
import MyComponent from 'my-react-components';

class LoginContainer extends Component {
    render() {
        return (<MyComponent />);
    }
}

This whole process works: the component is correctly rendered in my client application. My problem is that I fail to do the same if I want to transpile via Webpack instead of Babel . I'm interested in transpiling via Webpack, because I need to bundle more than just JS. I need to bundle CSS.

So I did a similar transpilation, via Webpack this time. The problem, is that when doing so, the import in the client application fails.

The JS console prints this error message:

反应错误

and the whole view ( LoginContainer.js ) fails to render.

The generated dist/main.js looks like this. Unlike the Babel version, it includes the code libraries we depend on (such as React). The transpiled code of MyComponent is visible at the bottom:

/******/ (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] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = 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;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/        }
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave like require
/******/    __webpack_require__.t = function(value, mode) {
/******/        if(mode & 1) value = __webpack_require__(value);
/******/        if(mode & 8) return value;
/******/        if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/        var ns = Object.create(null);
/******/        __webpack_require__.r(ns);
/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/        return ns;
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = "./src/index.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./node_modules/object-assign/index.js":
/*!*********************************************!*\
  !*** ./node_modules/object-assign/index.js ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("LIB CODE HERE");

/***/ }),

/***/ "./node_modules/prop-types/checkPropTypes.js":
/*!***************************************************!*\
  !*** ./node_modules/prop-types/checkPropTypes.js ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("LIB CODE HERE");

/***/ }),

/***/ "./node_modules/prop-types/lib/ReactPropTypesSecret.js":
/*!*************************************************************!*\
  !*** ./node_modules/prop-types/lib/ReactPropTypesSecret.js ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("LIB CODE HERE");

/***/ }),

/***/ "./node_modules/react/cjs/react.development.js":
/*!*****************************************************!*\
  !*** ./node_modules/react/cjs/react.development.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("LIB CODE HERE");

/***/ }),

/***/ "./node_modules/react/index.js":
/*!*************************************!*\
  !*** ./node_modules/react/index.js ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("LIB CODE HERE");

/***/ }),

/***/ "./src/index.js":
/*!**********************!*\
  !*** ./src/index.js ***!
  \**********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports[\"default\"] = void 0;\n\nvar _react = _interopRequireDefault(__webpack_require__(/*! react */ \"./node_modules/react/index.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\nvar MyComponent = function MyComponent() {\n  return /*#__PURE__*/_react[\"default\"].createElement(\"h1\", null, \"Hello from My Component\");\n};\n\nvar _default = MyComponent;\nexports[\"default\"] = _default;\n\n//# sourceURL=webpack:///./src/index.js?");

/***/ })

/******/ });

How can I transpile my components via Webpack instead of Babel , so that I can bundle CSS code together with the JS components?

Webpack does not transpile your code; it bundles it. What you're searching for are Webpack-Libraries .

I've already gave a similar answer here .

Basically, what you need is the following snippet in your webpack configuration:

module.exports = {
  //...
  output: {
    library: 'MyLibrary',
    // based on a fast look into the docs, I think the following are optional:
    libraryTarget: 'window',
    libraryExport: 'default'
  }
};

This exports a global Object called MyLibrary ( window.MyLibrary ). The problem here is, that this only exports your JavaScript files. You are still required to export CSS-Files and import them manually. That said, extend the webpack-config with a CSS-Extraction-Plugin :

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  plugins: [new MiniCssExtractPlugin({filename: 'styles.css'})],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};

This creates a styles.css file, which you can import in your clients code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM