s-leg3ndz
s-leg3ndz

Reputation: 3528

Module import return empty object

I try to create npm module using Webpack and TypeScript. After build my package and try to import it, i've an empty object, and not my default exported function.

You can see my configuration :

Webpack.js :

const webpack = require('webpack');
const path = require('path');

const config = {
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      {
        test: /\.ts(x)?$/,
        use: ['awesome-typescript-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          'postcss-loader'
        ]
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  }
};

module.exports = config;

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "strict": true,
    "noImplicitReturns": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5",
    "allowJs": true
  },
  "include": ["./src/**/*"]
}

My module is build, but default import return an empty object. I've try with example function :

const test = () => console.log('test');

export default test;

import test from 'my-module-name'; test() // test is not a function

Anyone have already create npm module using webpack and typescript ?

Thank you community !

Upvotes: 3

Views: 3112

Answers (1)

Thor-x86_128
Thor-x86_128

Reputation: 361

Based on this thread, you have to add libraryTarget: "commonjs2" to your webpack configuration.

Here's the example:

module.exports = {
    ...
    output: {
        path     : path.resolve(__dirname, 'dist'),
        filename : '[name].js',
        libraryTarget : 'commonjs2' // Add this line
    },
    ...
}

I have implemented this solution before and it also works on TypeScript + Webpack with similar problem.

Upvotes: 3

Related Questions