首页 > 解决方案 > Webpack 和 Typescript(ts-loader) 上的设置问题

问题描述

尝试使用 Webpack 和 ts-loader 设置 SolidJS。

不断遇到有关return功能的问题。

我在加载程序中究竟缺少什么来解决问题?

import { render } from "solid-js/web";
const App = () => {
  // return "Hello World"             // this works!
  return (<div> Hello World </div>)   // this doesnt work!
};
render(App, document.getElementById("app"));

错误日志输出:

> webpack --watch --progress --config webpack.config.js

asset index.js 1.56 KiB [emitted] (name: main)
./src/test.tsx 290 bytes [built] [code generated]

ERROR in ./src/test.tsx 6:12
Module parse failed: Unexpected token (6:12)
File was processed with these loaders:
 * ./node_modules/ts-loader/index.js
You may need an additional loader to handle the result of these loaders.
| const App = () => {
|     // return "Hello World"            // this works!
>     return (<div> Hello World </div>); // this doesnt work!
| };
| render(App, document.getElementById("app"));

webpack 5.47.0 compiled with 1 error in 2081 ms

webpack.config

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/test.tsx',
  module: {
    rules: [
      {
        use: 'ts-loader',
        test: /\.(ts|tsx)?$/,
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist')
  }
}

更新:

# tsconfig.json

{
  "compilerOptions": {
    "jsx": "preserve",
    "jsxImportSource": "solid-js",
   
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "node",
    "esModuleInterop": false
  },

  "include": ["src/**/*.ts", "src/**/*.tsx"],
  "exclude": ["node_modules"]
}

标签: javascripttypescriptwebpackts-loadersolid-js

解决方案


您需要添加 Babel。从 TypeScript 中保留 JSX 很好,但在最终捆绑之前仍然需要对其进行转换。babel-preset-solid 负责这个。否则 Webpack 不知道如何处理该 JSX。

一般来说,我只是将 Babel 与 TypeScript 预设一起使用。我知道这不会给你实时类型检查,只是剥离类型。Create React App 使用 fork-ts-checker-webpack-plugin 来解决该问题,并与 Babel 转换并行处理类型检查。


推荐阅读