node.jstypescriptwebpackwebpack-plugin

Is there a webpack config to bundle webpack plugin?


I am working on creating a webpack plugin. I have used typescript to code the plugin. I am trying to bundle the plugin code before I publish it on NPM. I am getting exception that my plugin class is not a constructor.

Please find below the directory structure:-

enter image description here

tsconfig.json:-

{
    "compilerOptions": {
        // Target latest version of ECMAScript.
        "target": "es5",
        // Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'.
        "module": "commonjs",
        // Search under node_modules for non-relative imports.
        "moduleResolution": "node",
        // Process & infer types from .js files.
        "allowJs": true,
        // Don't emit; allow Babel to transform files.
        "noEmit": false,
        "pretty": true,
        // Enable strictest settings like strictNullChecks & noImplicitAny.
        "strict": true,
        // Disallow features that require cross-file information for emit.
        "isolatedModules": true,
        // Import non-ES modules as default imports.
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true,
        "resolveJsonModule": true,
        "outDir": "dist/"
    },
    "include": [
        "src"
    ],
    "exclude": [
        "dist",
        "node_modules"
    ]
}

Webpack config:-

const path = require('path');

module.exports = {
    name: 'log-stylizer-webpack-plugin',
    entry: './src/index.ts',
    output: {
        filename: 'index.bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    mode: 'development',
    target: 'node',
    module: {
        rules: [
            {
                test: /\.ts?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            }
        ]
    },
    resolve: {
        extensions: ['.ts']
    }
};

Solution

  • In order to build a thing as a library with webpack, you have to specify the option output.libraryTarget to export things.

    {
      output: {
        // ...
        // `umd` is always a best choice in most cases
        // since it would work for all kind of module styles
        libraryTarget: 'umd',
      }
    }