Skip to content

Commit

Permalink
修复 Typescript target 导致的问题 (#145)
Browse files Browse the repository at this point in the history
* fix Typescript target

* update samples

* update preset config react
  • Loading branch information
nighca authored Aug 31, 2021
1 parent 98758fe commit 4669ee6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 29 deletions.
26 changes: 3 additions & 23 deletions preset-configs/react.json
Original file line number Diff line number Diff line change
@@ -1,28 +1,8 @@
{
"extends": "esnext",
"extends": "default",
"transforms": {
"js": {
"transformer": "jsx",
"config": {
"babelOptions": {
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
"@babel/plugin-proposal-class-properties"
]
}
}
},
"jsx": {
"transformer": "jsx",
"config": {
"babelOptions": {
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
"@babel/plugin-proposal-class-properties"
]
}
}
},
"js": "jsx",
"jsx": "jsx",
"svg@js": "svgr",
"svg@jsx": "svgr"
}
Expand Down
2 changes: 1 addition & 1 deletion samples
21 changes: 16 additions & 5 deletions src/webpack/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,22 @@ function addTransform(
transform.transformer === Transform.Tsx
)
const compilerOptions = {
// 这里设置为 ESNext(最新的规范能力),进一步的转换由 babel 处理
target: 'ESNext',
// enable tree-shaking,由 webpack 来做 module 格式的转换
module: 'ESNext',
// module 为 ESNext 时,moduleResolution 默认为 Classic(虽然 TS 文档不是这么说的),这里明确指定为 Node
// 这里设置为 ES2020(最新的规范能力),需要注意的是,这里设置 ESNext 可能是不合适的:
//
// > The special ESNext value refers to the highest version your version of TypeScript supports. This setting should be used with caution,
// > since it doesn’t mean the same thing between different TypeScript versions and can make upgrades less predictable.
// > - https://www.typescriptlang.org/tsconfig#target
//
// 这里 Typescript 处理的结果会交给 babel 处理;我们默认使用 @babel/preset-env,预期会支持最新的规范能力
// 然而我们使用的 Typescript 跟 babel (& @babel/preset-env) 行为之间可能会有 gap:
// 以 babel-plugin-proposal-class-properties 为例,在对应的 proposal 进入 stage 4 后,
// Typescript 会认为以 ESNext 为目标时,对应的语法不再需要转换;
// 而如果 builder 此时依赖了相对更新的 Typescript 版本,以及相对较旧的 babel (& @babel/preset-env) 版本
// 那么这里对 class properties 语法的支持就会有问题(Typescript & babel 都不会对它进行转换)
target: 'ES2020',
// 跟 target 保持一致,而不是设置为 CommonJS;由 webpack 来做 module 格式的转换以 enable tree shaking
module: 'ES2020',
// module 为 ES2020 时,moduleResolution 默认为 Classic(虽然 TS 文档不是这么说的),这里明确指定为 Node
moduleResolution: 'Node'
}
const tsLoaderOptions = {
Expand Down

0 comments on commit 4669ee6

Please sign in to comment.