Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

reactjs - webpack umd lib and external files

I want to package my react component as a umd lib.

below is webpack my setting:

module.exports = {
  devtool: 'eval',
  entry: [
    './lib/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'lib.js',
    library: 'lib',
    libraryTarget: 'umd'
  },
  resolve: {
    extensions: ['', '.js']
  },
  module: {
    loaders: [
      {
        test: /.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
      }
    ]
  },
  externals: {
    "react": "React"
  }
}

And then after I require the package in my other component in this way

example.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {lib} from "../dist/lib";

And above component's webpack setting is :

module.exports = {
  devtool: 'eval',
  entry: [
    './examples/example'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  resolve: {
    extensions: ['', '.js']
  },
  module: {
    loaders: [
      {
        test: /.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
      }
    ]
  }
}

After I compile the example.js file, it shows the error:

Line 3: Did you mean "react"?
  1 | (function webpackUniversalModuleDefinition(root, factory) {
  2 |   if(typeof exports === 'object' && typeof module === 'object')
> 3 |       module.exports = factory(require("React"));
    |                                    ^
  4 |   else if(typeof define === 'function' && define.amd)
  5 |       define(["React"], factory);
  6 |   else if(typeof exports === 'object')

I think the error is from the externals setting, cause after I remove externals: {react: "React"}, it works.

I search some related answers but can't fix it.

Does anyone have any idea of this? thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found the answer!

The reason is umd need to set the different external value (reference doc).

Because I set the external react as {react: React}, webpack would try to find a package named React.

So you need to set the different value in different module definition.

externals: {
  "react": {
    root: 'React',
    commonjs2: 'react',
    commonjs: 'react',
    amd: 'react'
  }
}

Then it fix!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...