简体   繁体   English

打字稿/节点意外令牌 *

[英]Typescript/Node Unexpected token *

I'm trying to update my app node backend to typescript and I keep hitting this syntax error:我正在尝试将我的应用程序节点后端更新为打字稿,但我一直遇到此语法错误:

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

SyntaxError: Unexpected token *

I have my tsconfig/webpack/server, etc set up as follows:我的 tsconfig/webpack/server 等设置如下:

server.ts服务器.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 : 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 : tsconfig.json

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

The build process succeeds, but I hit the syntaxError on run.构建过程成功,但我在运行时遇到了语法错误。 I have a react front end also set up using typescript / tsx and it works just fine.我有一个使用 typescript / tsx 设置的 React 前端,它工作得很好。 I seem to just be running into issues with the server.ts / node files.我似乎只是遇到了 server.ts / node 文件的问题。 I'm very new to trying to get this all set up, but I wanted practice making a site with numerous technologies (react/node/typescript/sass/webpack/etc).我对尝试设置这一切很陌生,但我想练习使用多种技术(react/node/typescript/sass/webpack/etc)制作网站。 So far I have everything except the typescript/node relationship.到目前为止,除了打字稿/节点关系之外,我拥有一切。

I had the same problem, after I realised that the tsconfig wasn't applied.在我意识到未应用 tsconfig 之后,我遇到了同样的问题。

If如果

"module": "commonjs" 

was in effect, you wouldn't have this error.实际上,你不会有这个错误。

I faced the same problem before.我之前也遇到过同样的问题。 I solve it by changing the import 'call':我通过更改导入“调用”来解决它:

From:从:

import * as express from 'express';

To:至:

const express = require('express');

As others have stated, the problem is that your tsconfig.json is not applied to server.ts.正如其他人所说,问题是您的 tsconfig.json 不适用于 server.ts。 You have left out important details of your setup which is why others cannot duplicate this problem.您遗漏了设置的重要细节,这就是其他人无法复制此问题的原因。

I have a good guess at what the issue is and having struggled with this identical problem myself, I will explain my guess here in the hope of helping some other poor soul being tormented by this issue.我对问题是什么有一个很好的猜测,并且我自己也在这个相同的问题上挣扎过,我将在这里解释我的猜测,希望能帮助其他一些被这个问题折磨的可怜的灵魂。

The basic problem is that your server code is in a different tree than your react code.基本问题是您的服务器代码与您的反应代码位于不同的树中。 This is why the tsconfig.json is not being applied to it since (I believe) it is outside the "./src/" path specified.这就是为什么 tsconfig.json 没有应用于它的原因,因为(我相信)它在指定的“./src/”路径之外。 (Perhaps "./website/src/"). (也许是“./website/src/”)。

You haven't shown us the package.json file but very likely the server entry is something like "server": "ts-node ./website/src/server.ts"您还没有向我们展示 package.json 文件,但很可能服务器条目类似于“server”:“ts-node ./website/src/server.ts”

To verify that the tsconfig.json application is the issue try this from the command line...要验证 tsconfig.json 应用程序是问题,请从命令行尝试此操作...

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

Chances are, things will start working.很有可能,事情会开始奏效。 Now the solution is probably as simple as adding another path your tsconfig.json includes.现在解决方案可能就像添加 tsconfig.json 包含的另一个路径一样简单。

So I came across this post on github where basically there are two sort of working methods presented since you're using a bundling tool targeted to es6 add所以我在 github 上看到了这篇文章,其中基本上有两种工作方法,因为您使用的是针对 es6 add 的捆绑工具

"allowSyntheticDefaultImports": true to ”compilerOptions” "allowSyntheticDefaultImports": true”compilerOptions” "allowSyntheticDefaultImports": true

Or change或者换

import express from "express";

to

import express = require('express');

This might be happening if your tsconfig.json isn't at the root of your project.如果您的tsconfig.json不在项目的根目录下,则可能会发生这种情况。 Configure webpack to point to your target config file (which you can alter with variables to point to dev and prod configurations).将 webpack 配置为指向您的目标配置文件(您可以使用变量对其进行更改以指向 dev 和 prod 配置)。

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

If set, will parse the TypeScript configuration file with given absolute path as base path.如果设置,将使用给定的绝对路径作为基本路径解析 TypeScript 配置文件。 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 (eg a NPM package), while the base path for ts-loader can remain the project root.选项上下文允许将选项 configFile 设置为项目根目录以外的路径(例如 NPM 包),而 ts-loader 的基本路径可以保留为项目根目录。

Try modifying your webpack.config.js file to have this:尝试修改您的webpack.config.js文件以具有以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM