【问题标题】:Typescript/Node Unexpected token *打字稿/节点意外令牌*
【发布时间】:2019-02-26 20:01:00
【问题描述】:

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

/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/**/*"
    ],
}

构建过程成功,但我在运行时遇到了 syntaxError。我也使用 typescript / tsx 设置了一个反应前端,它工作得很好。我似乎只是遇到了 server.ts / node 文件的问题。我对尝试进行这一切设置非常陌生,但我想练习使用多种技术(react/node/typescript/sass/webpack/etc)制作一个网站。到目前为止,除了打字稿/节点关系之外,我什么都有。

【问题讨论】:

  • 由于某种原因,您发布的 tsconfig 未应用。如果"module": "commonjs" 生效,则不会出现此错误。
  • 什么可能导致它没有被应用?我怎样才能减轻这种情况?
  • 可能有另一个 tsconfig 覆盖了这个,或者其他任何东西。问题特定于您的设置。请提供一种方法来复制问题 - 回购等。请参阅stackoverflow.com/help/mcve

标签: node.js typescript webpack commonjs


【解决方案1】:

正如其他人所说,问题在于您的 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 包含的另一个路径一样简单。

【讨论】:

    【解决方案2】:

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

    如果

    "module": "commonjs" 
    

    生效了,就不会出现这个错误了。

    【讨论】:

      【解决方案3】:

      我以前也遇到过同样的问题。我通过更改导入“调用”来解决它:

      发件人:

      import * as express from 'express';
      

      收件人:

      const express = require('express');
      

      【讨论】:

      【解决方案4】:

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

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

      如果设置,将使用给定的绝对路径作为基本路径解析 TypeScript 配置文件。默认情况下,配置文件的目录用作基本路径。配置文件中的相对路径在解析时相对于基本路径进行解析。选项上下文允许将选项 configFile 设置为项目根目录以外的路径(例如 NPM 包),而 ts-loader 的基本路径可以保留项目根目录。

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

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

      【讨论】:

        【解决方案5】:

        所以我在 github 上看到了 this 帖子,其中基本上有两种工作方法,因为您使用的是针对 es6 add 的捆绑工具

        "allowSyntheticDefaultImports": true”compilerOptions”

        或者改变

        import express from "express";
        

        import express = require('express');
        

        【讨论】:

        • 该链接似乎与我遇到的问题并不完全相关。该帖子中的 OP 能够将 'import * as express from 'express' 编译;我无法在具有这种语法的文件上使用 npm run start,这是我遇到的问题。建议的解决方案都不适合我。当我尝试从'express'导入快递时;我点击了“意外的令牌'express'”
        猜你喜欢
        • 2021-11-10
        • 2020-09-14
        • 2019-10-26
        • 2019-09-08
        • 2019-08-07
        • 1970-01-01
        • 2021-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多