Typescript/Node 意外的令牌 *

Typescript/Node Unexpected token *

我正在尝试将我的应用程序节点后端更新为打字稿,但我一直遇到此语法错误:

/Users/Shared/website/src/server.ts:1
(function (exports, require, module, __filename, __dirname) { import * 
as express from 'express';
                                                                 ^

SyntaxError: Unexpected token *

我的tsconfig/webpack/server等设置如下:

server.ts

import * as express from 'express';
import * as path from 'path';

const app = express();
const port = process.env.PORT || 3000;

app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', function(req, res, next){
    res.sendFile(path.resolve(__dirname, '/public', 'index.html'));
});

app.listen(port, () => console.log(`Listening on port ${port}!`));

webpack.config.json:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const outputDirectory = 'dist';

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: path.join(__dirname, outputDirectory)
    },
    mode: 'development',

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "ts-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" },

            {
                test: /\.scss$/,
                use: [
                    "style-loader", // creates style nodes from JS strings
                    "css-loader", // translates CSS into CommonJS
                    "sass-loader" // compiles Sass to CSS, using Node Sass by default
                ]
            }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
    },

    plugins: [
        new CleanWebpackPlugin([outputDirectory]),
        new HtmlWebpackPlugin({
          template: './public/index.html',
          favicon: './public/favicon.gif'
        }),
        new CopyWebpackPlugin([
            { from: 'public' }
        ])
    ]
};

tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react"
    },
    "include": [
        "./src/**/*"
    ],
}

构建过程成功,但我在 运行 上遇到了语法错误。我有一个反应前端也使用 typescript / tsx 设置,它工作得很好。我似乎 运行 正在处理 server.ts / 节点文件的问题。我对尝试设置这一切还很陌生,但我想练习使用多种技术 (react/node/typescript/sass/webpack/etc) 制作网站。到目前为止,我拥有除了 typescript/node 关系之外的所有内容。

所以我在 github 上遇到了 this post 那里基本上有两种工作方法,因为你使用的是针对 es6 的捆绑工具 add

"allowSyntheticDefaultImports": true”compilerOptions”

或更改

import express from "express";

import express = require('express');

如果您的 tsconfig.json 不在项目的根目录下,则可能会发生这种情况。配置 webpack 以指向您的目标配置文件(您可以使用变量更改以指向开发和生产配置)。

https://github.com/TypeStrong/ts-loader

If set, will parse the TypeScript configuration file with given absolute path as base path. Per default the directory of the configuration file is used as base path. Relative paths in the configuration file are resolved with respect to the base path when parsed. Option context allows to set option configFile to a path other than the project root (e.g. a NPM package), while the base path for ts-loader can remain the project root.

尝试修改您的 webpack.config.js 文件以使其具有以下内容:

module.exports = {
  ...
  module: {
    rules: [
      {
        options: {
          configFile: path.join(__dirname, "tsconfig.json")
        }
      }
    ]
  }
};

我以前遇到过同样的问题。我通过更改导入 'call':

来解决它

发件人:

import * as express from 'express';

收件人:

const express = require('express');

在我意识到未应用 tsconfig 后,我遇到了同样的问题。

如果

"module": "commonjs" 

生效,你不会有这个错误。

正如其他人所说,问题是您的 tsconfig.json 未应用于 server.ts。您遗漏了设置的重要细节,这就是其他人无法复制此问题的原因。

我很清楚这个问题是什么,我自己也曾遇到过同样的问题,我将在这里解释我的猜测,希望能帮助其他被这个问题折磨的可怜人。

基本问题是您的服务器代码与您的反应代码位于不同的树中。这就是 tsconfig.json 未应用于它的原因,因为(我相信)它在指定的“./src/”路径之外。 (也许是“./website/src/”)。

您没有向我们展示 package.json 文件,但服务器条目很可能类似于 "server": "ts-node ./website/src/server.ts"

要验证 tsconfig.json 应用程序是否存在问题,请从命令行尝试此操作...

$ ts-node -O '{\"module\":\"commonjs\"}' ./website/src/server.ts

很有可能,事情会开始奏效。现在解决方案可能就像添加另一个路径一样简单 tsconfig.json includes.