Webpack umd lib and external files

I want to pack my reaction component as umd lib.

below is webpack my setup:

 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, setting up the component web package:

 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 compiling the example.js file, an error is displayed:

 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 related to setting up externals, because after uninstalling externals: {react: "React"} it works.

I am looking for some related answers, but can't fix it.

Does anyone know about this? thanks.

+5
source share
1 answer

I found the answer!

Reason umd should set a different external value ( doc link).

Since I set the external response as {react: React} , webpack will try to find a package called React .

Therefore, you need to set a different value in the definition of another module.

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

Then he will fix it!

+15
source

Source: https://habr.com/ru/post/1238020/


All Articles