我正在编写一个需要在 nodejs 和浏览器中运行的库(通过脚本标签导入)。
我想用typescript写它,因为它方便,我也想用webpack,因为在某些时候我可能有其他内容或样式与之关联。
到目前为止,我已经成功地使库可用于 Node 和浏览器,但不知何故,我不能简单地将它导入另一个 typescript 项目并使用它是一个 typescript 库的事实。
这是我的 tsconfig.json
的样子:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"target": "es6",
"outDir": "ts/",
"strict": true
}
}
这是我的
webpack.config.js
:const path = require('path');
// PLATFORMS
var variants = [
{
target: "web",
filename: "index.browser.js"
},
{
target: "node",
filename: "index.node.js"
},
];
// CONFIG
var configGenerator = function (target, filename) {
return {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
target: target, // "web" is default
output: {
library: "myWebpackTypescriptLib",
libraryTarget: "umd",
filename: filename,
path: path.resolve(__dirname, 'dist')
}
};
};
// MAP PLATFORMS WITH CONFIGS
module.exports = variants.map(function(variant){
return configGenerator(variant.target, variant.filename)
})
从另一个 typescript 项目中,我尝试像这样导入它:
import myWebpackTypescriptLib from "myWebpackTypescriptLib";
但是通过这个导入,在我的文本编辑器中,我将无法访问 typescript 定义,并且在运行时出现以下错误:
ReferenceError: require is not defined
。我也尝试了以下方法,希望能有更好的结果:
import * as myWebpackTypescriptLib from "myWebpackTypescriptLib/src/index"
import * as myWebpackTypescriptLib from "myWebpackTypescriptLib/dist/ts/index.d"
有了这些,我成功地获得了 typescript 定义,但没有运行代码。
我在编译器中尝试了模块和目标的各种配置,但不知何故,目前的配置给了我最好的结果。我正在尝试做的事情中至少有两到三件事。
我已经学习了许多关于如何实现类似事情的不同教程,但我从来没有让这三个元素起作用。我一定还是错过了什么。
任何想法?
编辑:
这是我的目录结构的样子:
所有代码都在“/src/”目录下,webpack 在“/dist/”中为浏览器和 Node 创建版本。
文件/src/index.ts 从附加文件、插件、实用程序中的其他文件导入代码,它看起来像这样:
// UTILITIES
export * from "./utilities/someUtility";
// ADDITIONALS
export { someModule } from "./additionals/someModule";
let test = 10;
let echo = (a:any) => {
return a;
}
export default test;
export { echo };
所有的导入和导出都已正确设置,因为 webpack 为浏览器和 Node 渲染了所有内容。
最佳答案
所以我终于成功地让它工作了。
我在库的 package.json
中缺少对我的类型的正确声明,这就是它现在的样子,并且可以正常工作:)
{
"name": "myWebpackTypescriptLib",
"version": "0.0.1",
"description": "A webpack typescript library, usable in browser, node and other typescript projects.",
"main": "dist/index.node.js",
"types": "dist/ts/index.d.ts", // <---- this here was not properly set, it gives access to the typescript definitions when importing from other typescripts files
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode=development --progress --config webpack.config.js",
"prod": "webpack --mode=production --progress --config webpack.config.js"
},
...
}