【问题标题】:Publishing a TypeScript package to NPM with two kind of installation (import and CDN)使用两种安装(导入和 CDN)将 TypeScript 包发布到 NPM
【发布时间】:2019-07-11 14:30:20
【问题描述】:

我希望你将 TypeScript 项目发布到NPM。我正在使用 TypeScript Compiler (tsc) 将项目的 .ts 文件转换为输出 .js 文件。

因此,为了生成输出文件,我使用了简单的tsc 命令。

我的tsconfig.json

{
  "compilerOptions": {
    "outDir": "dist",
    "declaration": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5"
  }
}

发布后我可以通过以下方式安装我的包:

npm install mypackagename

并在打字稿中使用:

import MyLib from 'mypackagename'

有效!但我想提供两种安装方式:通过 npm/import(如上例所示)和通过CDN:

<script src="//unpkg.com/mypackagename"></script>

有可能吗?也许我需要使用一些捆绑器而不是 TypeScript 编译器?

现在不可能了,因为我不能直接在浏览器中使用 commonjs 代码。

【问题讨论】:

    标签: typescript npm


    【解决方案1】:

    我终于使用 Webpack 捆绑器配置:output.libraryoutput.libraryTargetUMD

    libraryTarget: 'umd' - 这会将你的库暴露在所有模块定义下,允许它与 CommonJS、AMD 和作为全局变量一起使用。查看UMD Repository 了解更多信息。

    所以,我的webpack.config.js 是:

    const path = require('path')
    
    module.exports = {
      entry: './src/index.ts',
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'my-output-file.js',
        library: 'MyLib',
        libraryTarget: 'umd',
        libraryExport: 'default',
      },
      module: {
        rules: [
          {
            test: /\.ts$/,
            use: 'ts-loader',
            exclude: /node_modules/,
          },
        ],
      },
    }
    

    ...而tsconfig.json 是:

    {
      "compilerOptions": {
        "outDir": "dist",
        "moduleResolution": "node",
        "target": "es5"
      },
      "exclude": [
        "node_modules",
        "dist"
      ]
    }
    

    多亏了这个,我的包可以通过import 在 ES6/TypeScript 中安装:

    import MyLib from 'my-lib'
    

    ...或通过unpkg CDN:

    <script src="//unpkg.com/my-lib@1.0.0"></script>
    <script>
        var inst = new MyLib()
    </script>
    

    我的项目源码:https://github.com/cichy380/simple-custom-event

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 2018-01-07
      • 1970-01-01
      • 2022-11-11
      • 2020-05-01
      • 2021-07-01
      • 2021-10-30
      • 1970-01-01
      • 2019-06-17
      相关资源
      最近更新 更多