使用TypeScript开发js库:@develon/js

webpack.config.js 相关字段

  • output.libraryTarget
    包括var(默认值,用于web场景)、umdcommonjs[2]amd等选项,如果webpack编译后在其它包中导入时一直是空对象{},那么你该了解一下这个字段了。
        output: {
            filename: '[name]/index.js',
            path: DIR_DIST,
            libraryTarget: 'umd', // 包括var(默认值,用于web场景)、commonjs[2]、amd等选项
        },
  • resolve.extensions
    你应该不想每次导入模块都写全称: import('./index'); 而不是 import('./index.ts');
        resolve: {
            extensions: ['.wasm', '.mjs', '.js', '.json', '.ts'], // 添加.ts解析
        },

添加babel支持

安装babel-loader及其依赖:

yarn add babel-loader @babel/core @babel/preset-env @babel/preset-typescript @babel/plugin-proposal-class-properties 

配置babel.config.json:

{
    "plugins": [
        "@babel/plugin-proposal-class-properties"
    ],
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "12.19.0"
                }
            }
        ],
        [
            "@babel/preset-typescript",
            {
                "allowNamespaces": false
            }
        ]
    ]
}

配置tsconfig.json文件

该文件不被Babel的TypeScript预设使用,只能控制一些IDE的行为,以及tsc构建。

tsconfig.json:
{
    "include": ["./src"],
    "compilerOptions": {
        "target": "ES6",
        "lib": ["ES6"],
        "module": "CommonJS",
        "moduleResolution": "Node",
        "declaration": true,
        "declarationDir": "./lib",
        "outDir": "./test",
    },
}

tsconfig.build.json:
{
    "extends": "./tsconfig.json",
    "exclude": ["./src/test.ts"], // test.ts由node-dev-server使用
    "compilerOptions": {
        "module": "UMD",
        "outDir": "./lib",
    },
}

end

posted @ 2020-10-28 11:21  develon  阅读(404)  评论(0编辑  收藏  举报