如何使用Webpack从Typescript构建JS库

qxsslcnc  于 12个月前  发布在  Webpack
关注(0)|答案(1)|浏览(128)

我创建了一个库项目结构,如下所示:

这是package.json

{
  "name": "testlib",
  "version": "1.0.0",
  "description": "library for test",
  "scripts": {
    "build:dev": "webpack --mode development",
    "build:prod": "webpack --mode production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^9.4.4",
    "typescript": "^5.1.6",
    "webpack": "^5.88.2",
    "webpack-cli": "^5.1.4"
  }
}

此tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "es6",
    "outDir": "./dist",
    "sourceMap": true
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

这是webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/index.ts',
    module: {
        rules: [
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                include: [path.resolve(__dirname, 'src')]
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.js']
    },
    output: {
        filename: 'testlib.js',
        library: 'testlib',
        path: path.resolve(__dirname, 'dist')
    }
}

这是index.ts

console.log('load test-lib index.ts');

export function myTestLib() {
    console.log('myTestLib function');
}

export {Sample1} from './Sample/sample1';

这是生成的testlib.js

var testlib;(()=>{"use strict";var e={d:(o,t)=>{for(var l in t)e.o(t,l)&&!e.o(o,l)&&Object.defineProperty(o,l,{enumerable:!0,get:t[l]})},o:(e,o)=>Object.prototype.hasOwnProperty.call(e,o),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},o={};e.r(o),e.d(o,{Sample1:()=>t,myTestLib:()=>l});class t{constructor(){console.log("this is sample 1")}}function l(){console.log("myTestLib function")}console.log("load test-lib index.ts"),testlib=o})();

这个testlib.js是正确的吗?我查看了教程视频,他们生成的 *.js文件跟我不一样。主要区别是webpack版本,typescript版本,ts-loader版本。其他人我按照教程设置这些配置。
如果我在我的angular项目中导入testlib.js。

import * as testLib from '../../../libs/testlib';
console.log(this.tag + 'awcLib function:', testLib.myTestLib());

它有错误:
TypeError:libs_testlib__WEBPACK_IMPORTED_MODULE_8_.myTestLib不是函数
最后我通过下面的方法解决了我的可重用库

library: {
    name: "testLib",
    type: "umd"
},
globalObject: "this",
sy5wg1nm

sy5wg1nm1#

这是Webpack在丑化代码时重命名函数名的正常行为。
testLib.myTestLib()是未知的。
您可以在缩小的输出中看到这一点(function l而不是function myTestLib):

function l(){console.log("myTestLib function")}console.log("...

window对象未更改。您可以将方法附加到此对象,然后访问它。

import { myTestLib } from '../../../libs/testlib';

window.testLib = {
  myTestLib
};

console.log(this.tag + 'awcLib function:', testLib.myTestLib());

相关问题