Leo Napoleon
Leo Napoleon

Reputation: 989

Can't import ES6 modules from webpack bundle

I have 2 local projects. One of them is a UI library for the second one, but they have to be separate. The second project is an application that should load the UI library from a single file - a bundle the UI library generates - index.js

I finished the UI library with a webpack 4 production config like the following:

const path = require('path')

const webpackConfig = {
  entry: {
    index: './src/styleguide/main.js',
  },
  devtool: 'source-map',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      { test: /\.js/, use: 'babel-loader' },
    ],
  },
  mode: 'production',
}

module.exports = webpackConfig;

To figure it out, let's use the following as my index.js

export default function Text () { return <p>Hello world</p> }

This yields me a "dist/index.js" file which is also my entry point in package.json


In the other project which needs to use the UI library, I am trying to do simply import UI from '../ui/dist/index.js'

But UI is either an empty object {} or undefined, or throws Uncaught Error: Minified React error #200; visit https://reactjs.org/docs/error-decoder.html?invariant=200 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.


I have tried setting library and libraryTarget, simplifying my scripts down to one liners without dependencies and I am getting very anxious about what I am missing. I would be grateful for any help!

Upvotes: 2

Views: 2381

Answers (1)

loveky
loveky

Reputation: 1012

Setting output.libraryTarget to commonjs2 in UI library should solve your problem.

Besides that, you may also want to set react as peerDependency in UI libiary and config webpack:

externals: {      
    // Don't bundle react      
    react: {          
        commonjs: "react",          
        commonjs2: "react",          
        amd: "React",          
        root: "React"      
    }  
},

this can lead to a much smaller bundle.

Upvotes: 1

Related Questions