[英]Can't get typescript to play nicely with babel in webpack
我正在嘗試將項目轉換為打字稿,其中一項要求是在類和函數參數上使用裝飾器:
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 Answer ,使用babel-plugin-transform-typescript-metadata解決了這個問題。 所以你的 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 一起工作)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.