【问题标题】:How can I solve my TypeScript/ESLint/Webpack transpiling problem如何解决我的 TypeScript/ESLint/Webpack 转译问题
【发布时间】:2020-04-29 17:33:13
【问题描述】:

我已经检查其他线程超过几天了;我在网上发现了几次相同的错误,但无法复制已发布的解决方案。为每个不同版本编写 babel/webpack 配置的方法有很多,这一事实并没有多大帮助。我正在运行 Webpack、TS 和 ESLint。我能够得到的“最佳情况”错误如下。我真的很想得到一些帮助! :[ 在很多事情中,我尝试将 tsx 转换为 jsx 并使用 jsx preserve 而不是 react。

终端编译错误:

ERROR in ./src/index.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\Users\Milo\Desktop\Programacion\zekeapp\src\index.tsx: Unexpected token (12:2)

  10 | 
  11 | ReactDOM.render(
> 12 |   <Provider store={store}>
     |   ^
  13 |     <Router>
  14 |       <Main />
  15 |     </Router>

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ThemeProvider } from 'styled-components';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import store from './store';
import Main from './containers/Main';
import { lightTheme } from './templates/theme';

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <Main />
    </Router>
  </Provider>,
  document.getElementById('root')
);

webpack.config.tsx

import * as path from 'path';

module.exports = {
  entry: path.join(__dirname, './src/index.tsx'),
  mode: 'production',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist/scripts')
  },

  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
  },

  module: {
    rules: [
      {
        test: /\.(js|jsx|tsx|ts)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      }
    ]
  }
};

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018" /* Specify ECMAScript target version: "ES3" (default), "ES5", "ES2015", "ES2016", "ES2017", "ES2018", "ES2019" or "ESNEXT". */,
    "module": "commonjs" /* Specify module code generation: "none", "commonjs", "amd", "system", "umd", "es2015", or "ESNext". */,
    "jsx": "preserve" /* Specify JSX code generation: "preserve", "react-native", or "react". */,
    "strict": true /* Enable all strict type-checking options. */,
    "noImplicitAny": false /* Raise error on expressions and declarations with an implied "any" type. */,
    "moduleResolution": "node" /* Specify module resolution strategy: "node" (Node.js) or "classic" (TypeScript pre-1.6). */,
    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
    "paths": {
      "#server/*": ["./server/*"],
      "#src/*": ["./src/*"]
    },
    "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
    "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
  }
}

【问题讨论】:

  • 要么将该 tsx 转换为 jsx,或者可能停止使用 "jsx": "preserve" 并使其生成 "react"?
  • 我已经尝试了这两种方法,它们都抛出了完全相同的错误,只是将“tsx”更改为“jsx”。
  • 原提示:put that in your post
  • 您是在使用create-react-app 进行构建还是从头开始设置的普通项目?
  • 它是从头开始设置的。

标签: javascript reactjs typescript webpack eslint


【解决方案1】:

按照官方React & Webpack 文档,我得到了一个示例项目。

进行这些更改:

  1. webpack.config.tsx 重命名为 webpack.config.js(由节点而非 TypeScript 运行)

  2. 安装 ts-loader 以转译 .ts/.tsx 文件:npm install --save-dev ts-loader

  3. 编辑webpack.config.js并配置ts-loader

这个例子也包括babel-loader

注意exclude: /node_modules/,configFile: path.resolve('./tsconfig.json'), 行,它们很重要并且需要正常工作(有关详细信息,请参阅下面的故障排除部分)

    // webpack.config.js
    {
        //...
        module: {
            rules: [
                {
                    test: /\.(js|jsx|tsx|ts)$/,
                    exclude: /node_modules/,
                    use: [
                        {
                            loader: 'babel-loader',
                        },
                        {
                            loader: 'ts-loader',
                            options: {
                                configFile: path.resolve('./tsconfig.json'),
                            },
                        },
                    ],
                }
            ]
        }
    }
  1. 编辑tsconfig.json 并添加这些设置:
    // tsconfig.json
    {
        "compilerOptions": {
            //...

            // Can use to "react" if you aren't using `babel-loader` and `@babel/preset-react` to handle jsx
            "jsx": "react" /* Specify JSX code generation: "preserve", "react-native", or "react". */,

            // Include these so the `react` imports work nicely:
            "esModuleInterop": true,
            "allowSyntheticDefaultImports": true
        }
    }
  1. 此时您应该能够构建项目:npx webpack
    $ npx webpack
    Hash: 184cde71516bcbc08144
    Version: webpack 4.41.5
    Time: 2558ms
    Built at: 01/13/2020 2:34:08 PM
        Asset     Size  Chunks             Chunk Names
    bundle.js  128 KiB       0  [emitted]  main
    Entrypoint main = bundle.js
    [2] ./src/index.tsx 498 bytes {0} [built]
    [8] ./src/Main.tsx 385 bytes {0} [built]
        + 7 hidden modules

2。示例文件

这是我的测试项目的文件内容:

package.json

{
    "devDependencies": {
        "@babel/core": "^7.8.0",
        "babel-loader": "^8.0.6",
        "ts-loader": "^6.2.1",
        "typescript": "^3.7.4",
        "webpack": "^4.41.5",
        "webpack-cli": "^3.3.10"
    },
    "dependencies": {
        "@types/react": "^16.9.17",
        "@types/react-dom": "^16.9.4",
        "react": "^16.12.0",
        "react-dom": "^16.12.0"
    }
}

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2018" /* Specify ECMAScript target version: "ES3" (default), "ES5", "ES2015", "ES2016", "ES2017", "ES2018", "ES2019" or "ESNEXT". */,
        "module": "commonjs" /* Specify module code generation: "none", "commonjs", "amd", "system", "umd", "es2015", or "ESNext". */,
        "strict": true /* Enable all strict type-checking options. */,
        "noImplicitAny": false /* Raise error on expressions and declarations with an implied "any" type. */,
        "moduleResolution": "node" /* Specify module resolution strategy: "node" (Node.js) or "classic" (TypeScript pre-1.6). */,
        "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
        "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
        "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
        "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
        "jsx": "react" /* Specify JSX code generation: "preserve", "react-native", or "react". */,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
    }
}

webpack.config.json

const path = require('path');

module.exports = {
    entry: path.join(__dirname, './src/index.tsx'),
    mode: 'production',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist/scripts')
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx|tsx|ts)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader',
                    },
                    {
                        loader: 'ts-loader',
                        options: {
                            configFile: path.resolve('./tsconfig.json'),
                        },
                    },
                ],
            }
        ]
    }
};

src/index.tsx

import React from 'react';
import ReactDOM from 'react-dom';

import Main from './Main';

ReactDOM.render( <Main />, document.getElementById('root') );

src/Main.tsx

import React from 'react';
import ReactDOM from 'react-dom';

export default function Main(){
    return (<h1>This is Main</h1>);
}

3。疑难解答

我在设置时遇到了这些问题 - 这是我找到的解决方案。

错误:您会收到如下错误:The 'files' list in config file 'tsconfig.json' is empty.

例如

ERROR in [tsl] ERROR
  TS18002: The 'files' list in config file 'tsconfig.json' is empty.

ERROR in ./src/index.tsx
Module build failed (from ./node_modules/ts-loader/index.js):
Error: error while parsing tsconfig.json

解决方案:解析完整的tsconfig.json路径

// webpack.config.js
{
    loader: 'ts-loader',
    options: {
        // configFile: './tsconfig.json', // !! WRONG
        configFile: path.resolve('./tsconfig.json'),    // CORRECT
    },
}

错误:您会收到如下错误:Module not found: Error: Can't resolve '...' in 'path-to-project/node_modules/react'

例如

ERROR in ./node_modules/react/index.js
Module not found: Error: Can't resolve './Main' in 'C:\webpack-typescript\node_modules\react'
@ ./node_modules/react/index.js 15:31-48
@ ./src/index.tsx

解决方案:确保将 node_modulests-loader 规则中排除。

// webpack.config.js
{
    module: {
        rules: [
            {
                test: /\.(js|jsx|tsx|ts)$/,
                exclude: /node_modules/, // <--- make sure this is here!
                // ...
            }
        ]
    }
}

【讨论】:

  • 好的,它几乎可以工作了。我没有遇到任何这些错误。但是我在编译时遇到了来自 webpack 的解析错误。它说'意外令牌'找到,这意味着配置声明中的语法似乎没有错误,只是没有找到。
  • 听起来 babel 在传递给它的保留 jsx 语法上失败了。你有没有配置 babel 使用@babel/preset-react
  • 是的,我有@babel react、env 和 typescript。不知道是什么东西,过几天再看。我向一位前老师询问了一个配置(老实说,它看起来 100% 相同)并且它有效,所以我坚持这样做。我花了大约 4 天时间尝试配置它。
猜你喜欢
  • 1970-01-01
  • 2018-12-24
  • 2020-11-27
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2018-05-17
相关资源
最近更新 更多