无法在 webpack 中获取打字稿与 babel 很好地配合



我正在尝试将项目转换为typescript,其中一个要求是在函数参数上都使用decorator:

function(@inject(TYPES.thing) thingy){...}

我觉得我真的很接近,只是错过了最后一块拼图:(

这是我的webpack配置:

return {
entry: path.resolve(__dirname, './src/js/Index.ts'),
output: {
filename: 'formr.bundle.js',
path: path.resolve(__dirname, `dist/${argv.mode === 'production' ? 'prod' : 'dev'}/js/`),
library: 'Formr',
libraryTarget: "umd"
},
devtool: devtool,
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".js", ".ts", ".tsx"]
},
mode: argv.mode,
module: {
rules: [
{
test: /.tsx?$/,
loader: 'babel-loader',
exclude: '/node_modules/',
query: {
presets: [
"@babel/typescript",
['@babel/preset-env', {
targets: {
browsers: "last 2 versions"
}
}]],
plugins: [
'lodash',
["@babel/plugin-proposal-decorators", { "legacy": true }],
"babel-plugin-parameter-decorator",
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-private-methods',
'@babel/plugin-proposal-optional-chaining'
]
}
},
{
test: /.js$/,
use: ["source-map-loader"],
enforce: "pre"
},
{
test: /.svg$/,
loader: 'svg-sprite-loader'
}
],
},
plugins: [
new SpriteLoaderPlugin(),
new LodashModuleReplacementPlugin()
]
}

和我的tsconfig:

{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "Node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "es5",
"lib": ["es6", "dom", "es2017.object"],
"types": ["reflect-metadata"],
"sourceMap": true,
"allowJs": true,
"allowSyntheticDefaultImports": true
},
"exclude": [
"node_modules"
],
"include": [
"./src/**/*"
]
}

我在构建过程中遇到的错误是:

ERROR in ./src/js/plugins/TranslationPlugin.ts
Module build failed (from ./node_modules/babel-loader/lib/index.js):
TypeError: /src/js/plugins/TranslationPlugin.ts: Cannot read property 'referencePaths' of undefined
at _loop (/node_modules/babel-plugin-parameter-decorator/lib/index.js:117:36)
....

如果我删除了babel-plugin-parameter-decorator插件,就不会出现错误,但我当然会收到不支持参数装饰器的错误。

根据这个SO答案,使用babel插件转换类型脚本元数据修复了这个问题。所以你的babel插件配置会变成:

...
plugins: [
'lodash',
"babel-plugin-transform-typescript-metadata"
["@babel/plugin-proposal-decorators", { legacy: true }],
"babel-plugin-parameter-decorator",
["@babel/plugin-proposal-class-properties", { loose: true }],
'babel/plugin-proposal-private-methods',
'babel/plugin-proposal-optional-chaining'
]
...

让我知道这是否有效,或者你是否已经修复了,因为我也感兴趣!(我无法使babel+typescript与TypeORM一起工作(

相关内容

最新更新