[英]Typescript syntax error on CommonJS/Node module: Unexpected token ':' on function param
此文件通过 TS 检查为有效,没有更多错误,但在运行时,我在我指定的任何 TS 上得到 Unexpected token ':',例如它立即在function (err: string)
这是我的构建和启动脚本。 我当然运行构建,然后运行启动:
"start": "node --trace-warnings dist/server.ts",
"build": "NODE_ENV=production webpack -p --env=prod",
api.ts
const _ = require('lodash'),
companyTable = require('./shared/data/companies.json'),
countryTable = require('./shared/data/countries.json'),
compression = require('compression'),
express = require('express'),
expressApp = (module.exports = express()),
historyApi = require('connect-history-api-fallback'),
oneYear = 31536000;
expressApp.use(compression());
module.exports = expressApp
.on('error', function (err: string) {
console.log(err);
})
.get('/api/v1/countries', (res: any) => {
res.json(
countryTable.map((country: any) => {
return _.pick(country, ['id', 'name', 'images']);
})
);
})
服务器.ts
const app = require('./api.js');
const cluster = require('cluster'),
os = require('os'),
port = process.env.PORT || 8080;
console.log(port);
if (cluster.isMaster) {
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
console.log('Ready on port %d', port);
} else {
app.listen(port, (err: string) => {
console.log(`express is listening on port ${port}`);
if (err) {
console.log('server startup error');
console.log(err);
}
});
}
tsconfig.json
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "es6", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["es6"], /* Specify library files to be included in the compilation. */
"moduleResolution": "node",
"allowJs": true, /* Allow javascript files to be compiled. */
"checkJs": true, /* Report errors in .js files. */
"jsx": "react",
"noImplicitAny": true,
"sourceMap": true, /* Generates corresponding '.map' file. */
"outDir": "dist", /* Redirect output structure to the directory. */
"rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"removeComments": true, /* Do not emit comments to output. */
"strict": true, /* Enable all strict type-checking options. */
"noUnusedLocals": true, /* Report errors on unused locals. */
"noUnusedParameters": true, /* Report errors on unused parameters. */
// "rootDirs": ["."], /* List of root folders whose combined content represents the structure of the project at runtime. */
"typeRoots": [
"node_modules/@types"
], /* List of folders to include type definitions from. */
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "resolveJsonModule": true,
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true
},
"include": [
"src"
],
"exclude": [
"/node_modules",
"/src/client/js/ink-config.js",
"**/test"
]
}
更新
所以有人指出了显而易见的。 询问为什么我的 dist 中有 a.ts 文件( server.ts
)和api.ts
。 那是因为我将它复制到我的 webpack.config.js 中:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const isProduction = process.env.NODE_ENV === 'production';
const html = () => {
return new HtmlWebPackPlugin({
template: path.resolve(__dirname, 'src/client', 'index.html'),
filename: 'index.html',
hash: true,
});
};
const copyAllOtherDistFiles = () => {
return new CopyPlugin({
patterns: [
{ from: 'src/client/assets', to: 'lib/assets' },
{ from: 'src/server.ts', to: './' },
{ from: 'src/api.ts', to: './' },
{ from: 'package.json', to: './' },
{ from: 'ext/ink-3.1.10/js/ink-all.min.js', to: 'lib/js' },
{ from: 'ext/ink-3.1.10/js/autoload.min.js', to: 'lib/js' },
{ from: 'ext/js/jquery-2.2.3.min.js', to: 'lib/js' },
{ from: 'ext/ink-3.1.10/css/ink.min.css', to: 'lib/css/ink.min.css' },
{ from: 'feed.xml', to: './' },
{
from: 'src/shared',
to: './shared',
globOptions: {
ignore: ['**/*suppressed.json'],
},
},
],
});
};
module.exports = {
entry: './src/client/index.tsx',
output: {
filename: 'scripts/app.[hash].bundle.js',
publicPath: '/',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
devtool: 'inline-source-map',
devServer: {
writeToDisk: true,
port: 8080,
},
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
splitChunks: {
cacheGroups: {
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
enforce: true,
},
},
},
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(tsx|ts)?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
},
{
test: /\.less$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: process.env.NODE_ENV === 'development',
},
},
'css-loader',
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: 'lib/assets/fonts',
},
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['url-loader'],
},
],
},
plugins: isProduction
? [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: isProduction ? 'lib/css/main.[hash].css' : 'main.css',
}),
html(),
copyAllOtherDistFiles(),
]
: [new CleanWebpackPlugin(), html(), copyAllOtherDistFiles()],
};
所以...我需要做一些不同的事情。 虽然我在开发过程中确实需要 server.ts 和 api.ts,但不知道如何编译然后复制这两个文件(在我创建的 web 捆绑包之外)。
所以我不完全确定直接复制文件的用例是什么 - 但让我通过指出如何在 output 目录中实现转译文件同时仍在开发中使用原始.ts
源文件来回答:
首先,您可以在开发中使用ts-node-dev
,这有助于您通过即时转译来运行原始源文件,因此您可以像使用node
二进制文件一样使用它,但在源文件上而不是在发出的文件上文件。 我使用与此类似的命令进行开发: NODE_ENV=development ts-node-dev --watch./src/server.ts --transpileOnly./src/server.ts
然后,对于生产,如果您没有在编译器选项中指定noEmit
选项,TypeScript 将转译文件并将文件发送到提供的outDir
。 因此,您可以使用节点二进制文件运行这些发出的文件: NODE_ENV=production node./dist/server.js
。 这将允许您从复制插件中删除源目录下的文件,因为 TypeScript 将为您在目录中转译并发出转译后的 js
编辑(来自评论):要仅包含您要转译的文件,您可以在 tsconfig 中指定include
中的文件: include: ['./src/api.ts', './src/server.ts']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.