带Typescript的webpack,如何创建一个模块以用作其他使用者的插件

时间:2018-12-15 15:23:23

标签: javascript typescript webpack umd

根据文档:https://webpack.js.org/configuration/output/

像这样配置输出:

module.exports = {
  //...
  output: {
    library: 'someLibName',
    libraryTarget: 'umd',
    filename: 'someLibName.js',
    auxiliaryComment: 'Test Comment'
  }
};

应输出如下内容:

(function webpackUniversalModuleDefinition(root, factory) {
  // Test Comment
  if(typeof exports === 'object' && typeof module === 'object')
    module.exports = factory(require('lodash'));
  // Test Comment
  else if(typeof define === 'function' && define.amd)
    define(['lodash'], factory);
  // Test Comment
  else if(typeof exports === 'object')
    exports['someLibName'] = factory(require('lodash'));
  // Test Comment
  else
    root['someLibName'] = factory(root['_']);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
  // ...
});

以便其他任何消费者都可以使用此模块。

但是在我的情况下,输出类似于:

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("React")):"function"==typeof define&&define.amd?define("lib",["React"],t):"object........"

我使用打字稿而不是普通的javascript,我丢失了什么或做错了什么?

我正在使用webpack“ ^ 4.27.1”,

这是我的webpack.config.prod.js

    const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    entry: "./src/index.tsx",
    mode: "production",
    output: {
        //path: resolve(__dirname, 'umd'),
        path: __dirname + "/dist",
        filename: 'lib.js',
        libraryTarget: 'umd',
        library: 'lib',
        umdNamedDefine: true,
        auxiliaryComment: 'Test Comment'
        //globalObject: 'this'
    },
    // output: {
    //     filename: "bundle.js",
    //     path: __dirname + "/dist"
    // },

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },

    plugins:[
        new UglifyJsPlugin(),
    ],

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

0 个答案:

没有答案