Error typescript emitted no output for

Expected Behaviour Get compiled js from ts Actual Behaviour Getting the following error: Module build failed: Error: Typescript emitted no output for C:xampphtdocsnode-apisrcjsserver.ts. at s...

Expected Behaviour

Get compiled js from ts

Actual Behaviour

Getting the following error:

Module build failed: Error: Typescript emitted no output for C:xampphtdocsnode-apisrcjsserver.ts.
at successLoader (C:xampphtdocsnode-apinode_modulests-loaderdistindex.js:39:15)
at Object.loader (C:xampphtdocsnode-apinode_modulests-loaderdistindex.js:21:12)
at eval (webpack:///./src/js/server.ts?:1:7)
at Object../src/js/server.ts (C:xampphtdocsnode-apidistjsserver.js:81:1)
at webpack_require (C:xampphtdocsnode-apidistjsserver.js:20:30)
at C:xampphtdocsnode-apidistjsserver.js:69:18
at Object. (C:xampphtdocsnode-apidistjsserver.js:72:10)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)

Steps to Reproduce the Problem

Use npm run dev in the repository below. Or use the following config files:

Webpack:

const path = require( 'path' ),
	CleanWebpackPlugin = require( 'clean-webpack-plugin' );

module.exports = env => {
	return {
		mode: env.dev ? 'development' : 'production',
		entry: {
			'server': './src/js/server.ts'
		},
		output: {
			path: __dirname,
			filename: './dist/js/[name].js',
		},
		externals: '/node_modules',
		module: {
			rules: [
				{
					test: /.js$/,
					exclude: ['/node_modules/', '/src/scss/'],
					use: [
						'babel-loader'
					]
				},
				{
					test: /.ts(x?)$/,
					exclude: ['/node_modules/', '/src/scss/'],
					use: [
						'babel-loader',
						'ts-loader',
					]
				},
				{
					test:  /.json$/,
					loader: 'json-loader'
				},
			]
		},
		resolve: {
			extensions: ['.js', '.ts', '.tsx'],
			alias: {
				'@': path.resolve(__dirname, './src/js')
			}
		},
		plugins: [
			new CleanWebpackPlugin(['./dist/js', './dist/css']),
		]
	}
};

Typescript:

{
	"compilerOptions": {
		"removeComments": true,
		"preserveConstEnums": true,
		"allowJs": true,
		"outDir": "./dist/js",
		"target": "es5",
		"moduleResolution": "node",
		"module": "es2015",
		"lib": [
			"es2015",
			"es2016"
		]
	},
	"exclude": [
		"./node_modules"
	]
}

Babel:

{
	"presets": [
		[
			"env", {
				"targets": {
					"node": "current"
				}
			}
		],
		"stage-2",
		"es2015"
	],
	"plugins": ["dynamic-import-node"]
}

Location of a Minimal Repository that Demonstrates the Issue.

https://github.com/SuperDJ/node-api

Содержание

  1. Module build failed: Error: Typescript emitted no output [*.d.ts] files #596
  2. Comments
  3. TypeScript emitted no output #22
  4. Comments
  5. bug(webpack): Typescript emitted no output #41
  6. Comments
  7. Compiler Option: noEmitOnError #91
  8. Comments
  9. Проблемы с импортом файлов Typescript и Js в модули узлов

Module build failed: Error: Typescript emitted no output [*.d.ts] files #596

I write some definition files in my vue project, it goes write when packing or building.
but throws exceptions when running unit-testing.
below is the errors:

WARNING in ./src/public/utils/wx.d.ts Module build failed: Error: Typescript emitted no output for /Users/shihao/Documents/Ldj/ldj_wechat_user/src/public/utils/wx.d.ts. at successLoader (/Users/shihao/Documents/Ldj/ldj_wechat_user/node_modules/ts-loader/dist/index.js:39:15) at Object.loader (/Users/shihao/Documents/Ldj/ldj_wechat_user/node_modules/ts-loader/dist/index.js:21:12) @ ./src ./(?!main.ts)(?!((S*.d.ts)|(S*.scss))$) @ ./test/unit/index.js 08 08 2017 09:55:31.729:INFO [karma]: Karma v1.7.0 server started at http://0.0.0.0:9876/ 08 08 2017 09:55:31.730:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency 08 08 2017 09:55:31.772:INFO [launcher]: Starting browser PhantomJS 08 08 2017 09:55:33.064:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket E2nThVXeM8NYRY3aAAAA with id 31493736 08 08 2017 09:55:33.339:WARN [reporter]: SourceMap position not found for trace: undefined PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR Error: Module build failed: Error: Typescript emitted no output for /Users/shihao/Documents/Ldj/ldj_wechat_user/src/components/amap/amap.d.ts. at successLoader (/Users/shihao/Documents/Ldj/ldj_wechat_user/node_modules/ts-loader/dist/index.js:39:15) at Object.loader (/Users/shihao/Documents/Ldj/ldj_wechat_user/node_modules/ts-loader/dist/index.js:21:12) at index.js:29910

—karma config file
`const webpackConfig = require(‘../../build/webpack.test.conf’);

module.exports = function (config) <
config.set( <
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the browsers array below.
browsers: [‘PhantomJS’],
frameworks: [‘mocha’, ‘sinon-chai’, ‘phantomjs-shim’],
reporters: [‘spec’, ‘coverage’],
files: [‘./index.js’],
preprocessors: <
‘./index.js’: [‘webpack’, ‘sourcemap’],
>,
webpack: webpackConfig,
webpackMiddleware: <
noInfo: true,
>,
‘log-level’: ‘info’,
coverageReporter: <
dir: ‘./coverage’,
reporters: [
,
,
],
>,
>);
>;`

typescript and ts-loader are latest versions.

anyone can help?

The text was updated successfully, but these errors were encountered:

Sorry I’m not a Vue user. Possibly @HerringtonDarkholme can help?

Источник

TypeScript emitted no output #22

Hi,
I’ve encountered something strange when using the plugin when writing typescript workers.
inside an electron environment and using electron-webpack and electron-builder for bundling and building.

When I run the app in dev mode ( yarn dev ), everything get’s transpiled, bundled and running OK, but whenever trying to build the app into an executable, I get errors from typescript, failing the build.

ERROR in ./src/main/workers/myWorker.ts (./node_modules/ts-loader??ref—8-0!./node_modules/eslint-loader??ref—6!./src/main/workers/myWorker.ts)
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for C:DevRepositoriesmy-reposrcmainworkersmyWorker.ts.
at makeSourceMapAndFinish (C:DevRepositoriesmy-reponode_modulests-loaderdistindex.js:80:15)
at successLoader (C:DevRepositoriesmy-reponode_modulests-loaderdistindex.js:68:9)
at Object.loader (C:DevRepositoriesmy-reponode_modulests-loaderdistindex.js:22:12)

Last time it happened to me, the problem was really petty.
When I defined my array as const myArray: MyType[] = []; , typescript failed to build. Eventually, only after changing the code to be:
const myArray: Array = new Array();
it worked.

now I’m facing some another similar issue , that prevents me to do some kind of easy reduce code over an array.

my webpack is based upon electron-webpack’s defaults, and I added this to allow node’s built-in api inside workers:

I have tried both with and without ts-node installed, the result is the same.

There are actually 2 errors listed, the one I’ve mentioned above. and this one:

ERROR in ./src/main/workers/myWorker.ts (./node_modules/threads-plugin/dist/loader.js?<«name»:»3″>!./src/main/workers/myWorker.ts)
Module build failed (from ./node_modules/threads-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for C:DevRepositoriesmy-reposrcmainworkersmyWorker.ts.
at makeSourceMapAndFinish (C:DevRepositoriesmy-reponode_modulests-loaderdistindex.js:80:15)
at successLoader (C:DevRepositoriesmy-reponode_modulests-loaderdistindex.js:68:9)
at Object.loader (C:DevRepositoriesmy-reponode_modulests-loaderdistindex.js:22:12)
at C:DevRepositoriesmy-reponode_moduleswebpacklibNormalModule.js:316:20
at C:DevRepositoriesmy-reponode_modulesloader-runnerlibLoaderRunner.js:367:11
at C:DevRepositoriesmy-reponode_modulesloader-runnerlibLoaderRunner.js:233:18
at runSyncOrAsync (C:DevRepositoriesmy-reponode_modulesloader-runnerlibLoaderRunner.js:143:3)
at iterateNormalLoaders (C:DevRepositoriesmy-reponode_modulesloader-runnerlibLoaderRunner.js:232:2)
at iterateNormalLoaders (C:DevRepositoriesmy-reponode_modulesloader-runnerlibLoaderRunner.js:221:10)
at C:DevRepositoriesmy-reponode_modulesloader-runnerlibLoaderRunner.js:236:3
at Object.context.callback (C:DevRepositoriesmy-reponode_modulesloader-runnerlibLoaderRunner.js:111:13)
at Object.module.exports (C:DevRepositoriesmy-reponode_moduleseslint-loaderindex.js:274:11)
@ ./src/main/ipc/workerDispatchers/myWorker.ts 1:0-158
@ ./src/main/ipc/index.ts
@ ./src/main/index.ts
@ multi ./src/main/index.ts

I can’t tell the actual typescript error, even if there is one, because it’s not showing at the output.
I’m afraid something in my configurations isn’t defined properly.
would love to get your advice.
What am I missing?

The text was updated successfully, but these errors were encountered:

Источник

bug(webpack): Typescript emitted no output #41

  • I’m submitting a .
  • bug report
  • feature request
  • Which parts of preboot are affected by this issue?
  • server side
  • client side
  • inline
  • build process
  • docs
  • tests
  • Do you want to request a feature or report a bug?

What is the current behavior?

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem by creating a github repo.

  1. Prepare a Universal bundle as specified here
  2. Attempt to compile using npm run build:dynamic
  3. Receive the below error
  • What is the expected behavior?

Should be able to compile a bundle that relies on preboot

  • What is the motivation / use case for changing the behavior?

Unable to use webpack to build a nodejs bundle from a TypeScript source

  • Please tell us about your environment:
  • Language: [all | TypeScript 2.5.2 | ES6/7 | ES5 ]
  • OS: [all | Mac OS X | Windows | Linux ]
  • Platform: [all | NodeJs | Java | PHP | .Net | Ruby]
  • Other information (e.g. detailed explanation, stacktraces, related issues, suggestions how to fix, links for us to have context, eg. stackoverflow, gitter, etc)

The text was updated successfully, but these errors were encountered:

Источник

Compiler Option: noEmitOnError #91

I’m using the noEmitOnError option in tsconfig.json and I get a bunch of Typescript emitted no output for . errors each time there is an error in one of my TypeScript files. It propagates to dependent files and it’s getting really annoying, considering TypeScript errors are already properly reported. Can we remove this error or maybe suppress it if noEmitOnError is true?

The text was updated successfully, but these errors were encountered:

I agree this needs to be looked at. If you don’t mind I’m going to hijack your issue a little bit to make it part of the effort to evaluate all compiler options in detail.

Another part of this, I believe, is being able to fail a build. For example, if webpack is being run as part of a larger build process, people want to be able to get an error code out of webpack if there is a TS error so that the build fails. I think that the right way to handle that is using noEmitOnError .

I’m probably going to work around this at the moment by removing the noEmitOnError option which is not really crucial, or I could do a regex and remove those errors from my side. I already have to process and format them in a way the IDE can understand.

Out of curiosity, when you process the errors are you making use of the undocumented error information that’s provided? I threw that stuff on there to help people who are processing the raw errors but I have no clue if people actually use it.

I will have to double-check from work, tomorrow, but most likely I am using those properties. I’m formatting all errors to match the output pattern of tsc. I also have a modified pattern configured in VSCode, which allows WEBPACK|TSLINT in place of TS#### error codes. This way the IDE maps errors/warnings coming from ts/ts-loader, tslint or webpack itself (there are also some legacy JS files in the project).

I’m also relying on some undocumented properties on the webpack error objects too, and that isn’t really production quality, but it worked so far. Being able to include the tasks.json setup in the project itself also allows for a seamless build from VSCode.

Note : noEmitOnError can slow down builds as TypeScript will validate the entire project even if emitting a single file.

@basarat , I didn’t know that. Thanks!

@jbrantly , looks like I’m using both rawMessage and location .

Источник

Проблемы с импортом файлов Typescript и Js в модули узлов

Я импортирую папку модуля узла, которая содержит файлы Typescript и JS. Я использую ts-loader для машинописного текста, но по какой-то причине он создает длинный список ошибок, и я думаю, это из-за того, что оба файла находятся вместе. Я сам не могу трогать эти файлы, может, есть способ лучше настроить ts-loader?

Это мой tsconfig.json

некоторые из ошибок:

ERROR in ./node_modules/project/frontend/react/shared/inputs/smallcolorinput.tsx Module build failed (from ./node_modules/ts-loader/index.js): Error: Typescript emitted no output for ../FrontEnd/ProjectFolder/node_modules/project/frontend/react/shared/inputs/smallcolorinput.tsx. at successLoader (../FrontEnd/ProjectFolder/node_modules/ts-loader/dist/index.js:41:15) at Object.loader (../FrontEnd/ProjectFolder/node_modules/ts-loader/dist/index.js:21:12) @ ./node_modules/project/frontend/react/shared/views/FontSettings.jsx 13:23-59 @ ./node_modules/project/frontend/react/shared/views/ThemeEditor.jsx @ ./node_modules/project/frontend/react/editor/editor.jsx @ ./electron/views/Edit.tsx

Это конфигурация веб-пакета:

Можете добавить к вопросу какие-нибудь ошибки?

Я добавил ошибку ниже, она повторяется несколько раз.

Какая у вас конфигурация Webpack? Были ли файлы JavaScript в node_modules произведены путем компиляции файлов TypeScript (например, a.ts -> a.js ) или они разные?

Веб-пакет тоже тот, я думаю, выглядит неплохо.

Спасибо за настройку Webpack. Были ли файлы JavaScript в node_modules произведены путем компиляции файлов TypeScript (например, a.ts -> a.js ) или они разные? Возможно, я не смогу решить эту проблему самостоятельно, но я пытаюсь собрать информацию, которая может понадобиться другим людям для решения этой проблемы.

Да, верно, они создаются путем компиляции a.ts в a.js.

У меня нет идей. Поскольку мой ответ не помог, я удалю его, чтобы вопрос снова стал без ответа.

Источник

Question:

I am using typescript and vue 3 to develop a google chrome extension. when I am importing an enum in typescript using this code:

import { MessageType } from '@/model/message/MessageType';

when compile the typescript code, shows error:

./src/background/index.ts 39 bytes [built] [1 error]

ERROR in ./src/background/index.ts
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for /Users/dolphin/source/reddwarf/frontend/reddwarf-translate-plugin/src/background/index.ts.
    at makeSourceMapAndFinish (/Users/dolphin/source/reddwarf/frontend/reddwarf-translate-plugin/node_modules/ts-loader/dist/index.js:52:18)
    at successLoader (/Users/dolphin/source/reddwarf/frontend/reddwarf-translate-plugin/node_modules/ts-loader/dist/index.js:39:5)
    at Object.loader (/Users/dolphin/source/reddwarf/frontend/reddwarf-translate-plugin/node_modules/ts-loader/dist/index.js:22:5)

ERROR in /Users/dolphin/source/reddwarf/frontend/reddwarf-translate-plugin/src/background/index.ts

why did this happen? this is the enum define:

export enum MessageType {
    TRANSLATE = "TRANSLATE"
}

and this is the webpack 5.x config:

 const path = require('path');
  const webpack = require( 'webpack' );
  const MiniCssExtractPlugin = require( 'mini-css-extract-plugin');
  const HtmlWebpackPlugin = require( 'html-webpack-plugin');
  const CopyPlugin = require("copy-webpack-plugin");
  const { VueLoaderPlugin } = require("vue-loader");

  module.exports = {
    entry : {
      'popup/popup' : './src/popup/',
      'background/background': './src/background' 
    } ,
    resolve: {
      extensions: ['.tsx', '.ts', '.js'],
      alias: {
          vue: 'vue/dist/vue.esm-bundler.js',
          process: 'process/browser',
          //'@': path.resolve(__dirname, 'src'),
      },
    },
    output : {
      path : path.resolve(__dirname, '../../bundle') ,
      filename : '[name].js'
    },
    module : {
      rules : [
        {
          test: /.ts$/,
          loader: 'ts-loader',
          options: {
            appendTsSuffixTo: [/.vue$/]
          },
          exclude: /node_modules|.d.ts$/
        },
        {
          test: /.d.ts$/,
          loader: 'ignore-loader'
        },
        {
          test: /.vue$/,
          loader: 'vue-loader'
        },
        {
          test : /.js$/ ,
          exclude : [ /node_modules(?!(/|\?\)(translation.js|selection-widget|connect.io|chrome-env)1)/ ] ,
          loader : 'babel-loader'
        } ,
        {
          test: /.css$/i,
          use: [MiniCssExtractPlugin.loader, "css-loader"],
        },
        {
          test : /.(scss)$/ ,
          use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
        }
      ]
    },
    plugins : [
      new webpack.ProvidePlugin({
        process: 'process/browser',
      }),
      new VueLoaderPlugin(),
      new CopyPlugin({
        patterns: [
          { from: "src/manifest.json", to: "manifest.json" },
          { from: "src/resource/image", to: "resource/image" },
        ],
      }),
      new MiniCssExtractPlugin({
        filename: "[name].css",
        chunkFilename: "[id].css",
      }),
      new HtmlWebpackPlugin({
        filename: 'popup/popup.html',
        template: 'src/popup/index.html'
      }),
      new webpack.DefinePlugin({
        __VUE_OPTIONS_API__: false,
        __VUE_PROD_DEVTOOLS__: false,
      }),
    ]
  };

why did this happen? what should I do to avoid this problem?

Answer:

This error can be caused by a number of things. One possibility is that you have not included a file that defines the enum. Make sure that the file that contains the enum definition is included in your project.

It may be due to an incorrect usage of the @ symbol when importing an enum in TypeScript. Make sure that the @ symbol is used when importing an enum and that the name of the enum is enclosed in quotes.

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com

29.03.2020, 18:49. Показов 4254. Ответов 1


Всем привет.
Пытаюсь собрать приложение React webpack-ом, но выдает ошибку:

Кликните здесь для просмотра всего текста

ERROR in ./src/index.tsx
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for D:ProjectsJavaScriptReactFoodkortsrcindex.ts x.
at makeSourceMapAndFinish (D:ProjectsJavaScriptReactFoodkortnode_module sts-loaderdistindex.js:80:15)
at successLoader (D:ProjectsJavaScriptReactFoodkortnode_module sts-loaderdistindex.js:68:9)
at Object.loader (D:ProjectsJavaScriptReactFoodkortnode_module sts-loaderdistindex.js:22:12)

ERROR in multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.tsx main[0]

ERROR in multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.tsx main[1]
Child HtmlWebpackCompiler:
1 asset
Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
[./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 588 bytes {HtmlWebpackPlugin_0} [built]
i 「wdm」: Failed to compile.

Пытался убрать или поставить в false параметр «noEmit» в tsconfig — ошибка поменялась на следующую:

Кликните здесь для просмотра всего текста

ERROR in multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.tsx main[0]

ERROR in multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.tsx main[1]

ERROR in ./src/index.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./src/index.tsx 2:0-33 4:0-8

ERROR in ./src/index.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./src/index.tsx 1:0-26 4:16-21

ERROR in ./src/components/App.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./src/components/App.tsx 14:0-41 23:16-21 26:2-11
@ ./src/index.tsx

ERROR in ./src/components/Forms/SimpleForm.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./src/components/Forms/SimpleForm.tsx 14:0-26 24:16-21 25:12-17 35:2-7
@ ./src/components/App.tsx
@ ./src/index.tsx

ERROR in ./node_modules/antd/dist/antd.css
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./node_modules/antd/dist/antd.css 1:10-81
@ ./src/components/Forms/SimpleForm.tsx
@ ./src/components/App.tsx
@ ./src/index.tsx

ERROR in ./src/styles/App.css
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./src/styles/App.css 1:10-94
@ ./src/components/App.tsx
@ ./src/index.tsx

ERROR in ./src/components/Forms/SimpleForm.tsx
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./src/components/Forms/SimpleForm.tsx 16:0-28 24:36-40 25:32-36 36:14-18
@ ./src/components/App.tsx
@ ./src/index.tsx

ERROR in ./src/styles/App.css (./node_modules/css-loader/dist/cjs.js!./src/styles/App.css)
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./src/styles/App.css (./node_modules/css-loader/dist/cjs.js!./src/styles/App.css) 2:34-94
@ ./src/styles/App.css
@ ./src/components/App.tsx
@ ./src/index.tsx

ERROR in ./node_modules/antd/dist/antd.css (./node_modules/css-loader/dist/cjs.js!./node_modules/antd/dist/antd.css)
Module not found: Error: Can’t resolve ‘source-map-loader’ in ‘D:ProjectsJavaScriptReactFoodkort’
@ ./node_modules/antd/dist/antd.css (./node_modules/css-loader/dist/cjs.js!./node_modules/antd/dist/antd.css) 2:34-81
@ ./node_modules/antd/dist/antd.css
@ ./src/components/Forms/SimpleForm.tsx
@ ./src/components/App.tsx
@ ./src/index.tsx
Child HtmlWebpackCompiler:
1 asset
Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
[./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 588 bytes {HtmlWebpackPlugin_0} [built]
i 「wdm」: Failed to compile.

Содержимое файлов:
package.json:

{
«name»: «Foodkort»,
«version»: «1.0.0»,
«description»: «»,
«main»: «./src/index.tsx»,
«scripts»: {
«test»: «echo «Error: no test specified» && exit 1″,
«start»: «webpack-dev-server —mode development —open —hot»,
«start-prod»: «webpack-dev-server —mode production —open»,
«build»: «webpack —mode production»
},
«keywords»: [],
«author»: «Игорь Игоревич Иванов»,
«license»: «ISC»,
«devDependencies»: {
«@babel/core»: «^7.9.0»,
«@babel/preset-env»: «^7.9.0»,
«@babel/preset-react»: «^7.9.4»,
«@types/react»: «^16.9.26»,
«@types/react-dom»: «^16.9.5»,
«@typescript-eslint/eslint-plugin»: «^2.25.0»,
«@typescript-eslint/parser»: «^2.25.0»,
«babel-loader»: «^8.1.0»,
«css-loader»: «^3.4.2»,
«eslint»: «^6.8.0»,
«eslint-config-standard»: «^14.1.1»,
«eslint-plugin-import»: «^2.20.1»,
«eslint-plugin-node»: «^11.1.0»,
«eslint-plugin-promise»: «^4.2.1»,
«eslint-plugin-react»: «^7.19.0»,
«eslint-plugin-standard»: «^4.0.1»,
«html-webpack-plugin»: «^4.0.2»,
«style-loader»: «^1.1.3»,
«ts-loader»: «^6.2.2»,
«typescript»: «^3.8.3»,
«webpack»: «^4.42.1»,
«webpack-cli»: «^3.3.11»,
«webpack-dev-server»: «^3.10.3»
},
«dependencies»: {
«antd»: «^3.26.13»,
«react»: «^16.13.1»,
«react-dom»: «^16.13.1»
}
}

tsconfig.json

{
«compilerOptions»: {
«target»: «es5»,
«lib»: [
«dom»,
«dom.iterable»,
«esnext»
],
«allowJs»: true,
«skipLibCheck»: true,
«esModuleInterop»: true,
«allowSyntheticDefaultImports»: true,
«strict»: true,
«forceConsistentCasingInFileNames»: true,
«module»: «esnext»,
«moduleResolution»: «node»,
«resolveJsonModule»: true,
«isolatedModules»: true,
//»noEmit»: true,
«jsx»: «react»,
«experimentalDecorators»: false
},
«include»: [
«./src»
],
«exclude»: [«src/**/*.test.(tsx|jsx|ts|js)»]
}

webpack.config.js

const path = require(«path»);
const HtmlWebpackPlugin = require(«html-webpack-plugin»);

module.exports = {
devtool: «source-map»,

entry: path.join(__dirname, «src»,»index.tsx»),
output: {
path: path.join(__dirname, «/dist»),
filename: «index_bundle.js»
},
module: {
rules: [
{
test: /(?<!.d).tsx?$/,
exclude: /node_modules/,
use: {
loader: «ts-loader»
}
},
{
test: /.css$/,
use: [«style-loader», «css-loader»]
},
{
enforce: «pre»,
test: /.js$/,
loader: «source-map-loader»
}
]
},
resolve: {
extensions: [«.ts», «.tsx»]
},
plugins: [
new HtmlWebpackPlugin({
template: «./src/index.html»
})
]
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



При компиляции webpack получаю такую ошибку:

Hash: 58d821e2954fef96ec41
Version: webpack 4.41.0
Time: 3249ms
Built at: 09/27/2019 6:39:50 PM
 2 assets
Entrypoint main = main.js main.js.map
[0] ./src/index.tsx 526 bytes {0} [built] [failed] [1 error]

ERROR in ./src/index.tsx
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for //frontend/src/index.tsx.
    at makeSourceMapAndFinish (/frontend/node_modules/ts-loader/dist/index.js:80:15)
    at successLoader (/frontend/node_modules/ts-loader/dist/inde

x.js:68:9)
    at Object.loader (/frontend/node_modules/ts-loader/dist/index.js:22:12)

ERROR in /frontend/src/react-app-env.ts
[tsl] ERROR in /frontend/src/react-app-env.ts(1,1)
      TS1208: All files must be modules when the '--isolatedModules' flag is provided.

Вот мой webpac.config.js

module.exports = {
    mode: "production",

    entry: './src/index.tsx',

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

    module: {
        rules: [
            {
                test: /.ts(x?)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "ts-loader"
                    }
                ]
            },
            {
                enforce: "pre",
                test: /.js$/,
                loader: "source-map-loader"
            }
        ]
    },
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

Вот tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCh

eck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

Вот package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/core": "^7.6.2",
    "@babel/preset-env": "^7.6.2",
    "@types/jest": "24.0.18",
    "@types/node": "12.7.8",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-scripts": "3.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/react": "^16.9.3",
    "@types/react-dom": "^16.9.1",
    "source-map-loader": "^0.2.4",
    "ts-loader": "^6.1.2",
    "typescript": "^3.6.3",
    "webpack": "^4.41.0",
    "webpack-cli": "^3.3.9"
  }
}

Я вообще хз, что делать.

У меня аналогичная проблема, однако она проявляется только тогда, когда я удалил пару записей из конфигурации своего веб-пакета. Понятия не имею, почему. Модуль даже не выводил данные ни в одну из удаленных мной записей.

Я использую новый машинописный текст / веб-пакет:
ts-loader: 0.8.2
webpack: 2.1.0-beta.21
tsc: 2.0.2

Обновлять:
Я обновил рассматриваемый компонент, чтобы он включал предварительно скомпилированные файлы js. Затем он работал без проблем. Я думаю, проблема в том, что загрузчик ts может не компилировать компоненты в node_modules при определенных обстоятельствах, даже если модули node не исключены в tsconfig.json.

Энгуэрран,
Не могли бы вы объяснить, как вы исправили ошибку. Я не могу следить за вашим комментарием, касающимся версий скрипта типа.

Также получить это с TS 2.0.3, а понижение версии TS не является вариантом из-за некоторых вещей, которые мы используем.

Как ни странно, если я npm связываю рассматриваемый модуль, он работает нормально, но опять же, это не совсем идеальное решение

Если кто-то может создать репо, демонстрирующее проблему, это может быть полезно. Из того, что люди сказали, это репо должно работать с TS 1.8, но не работать с TS 2.0. Если он существует, то это отправная точка для расследования этого вопроса.

@johnnyreilly https://github.com/skysteve/ts-bug-example-2 — это самый простой пример, который я мог получить. Сообщите мне, если вам понадобятся какие-либо дополнительные сведения, но, конечно же, на моем Mac на узле v 6.6 я могу воспроизвести проблему.

Обновлять

Если я обновлю файл tsconfig.json, чтобы удалить флаг «allowJS», ошибка, похоже, исчезнет (ветка https://github.com/skysteve/ts-bug-example-2/tree/disallow-js). Это нормально в этом простом проекте, но в моем реальном проекте мне нужно смешивать JS и TS, так что это неправильное решение.

Не могли бы вы повторить тест с ts-loader v0.9.3? Мы только что добавили поддержку allowJs которая может решить проблему.

Проблема сохраняется с 0.9.3

typestyle кажется несовместимым с ts-loader.

ERROR in ./~/typestyle/csx/index.ts
Module build failed: Error: Typescript emitted no output for /Users/syedb/REPOS/tmp/browsertypestyle/node_modules/typestyle/csx/index.ts
    at Object.loader (/Users/syedb/REPOS/tmp/browsertypestyle/node_modules/ts-loader/dist/index.js:27:15)

Пример проекта:
browsertypestyle.zip

Используйте npm install и npm start . Получаем ошибку.

Примечание: awesome-typescript-loader работает с ним, но у него есть свои проблемы, о которых я бы не хотел здесь рассказывать. Упоминание об этом как о чем-то, что можно отладить, чтобы выяснить основную причину / исправить: rose:

Спасибо за репро @basarat — я бы лучше забыл об этой проблеме. Я постараюсь взглянуть, когда у меня будет минутка. Надеюсь, вам весело в США — какое время вы выбрали для отпуска!

Совет всем авторам библиотек, отправляющих файлы .ts в качестве _основного_ способа использования ts: я проделал то же самое для стиля ввода в качестве эксперимента, и результаты были неудовлетворительными и никогда не вернусь к нему снова. Причины, описанные здесь: https://github.com/typestyle/typestyle/releases/tag/v0.7.0 Предлагаем вам также использовать outDir + .js + .d.ts : rose : ❤️

@johnnyreilly урок был болезненным. Но сетапа нет:

  • tsconfig
  • код в src/
  • outDir в lib/
  • Сделано: роза:

: tulip: Значит, изменения, о которых вы говорили, в ts-loader все еще в силе?

У меня нет желания реализовать это, и я бы никому не рекомендовал писать пакет, который отправляет .ts + .js а вместо этого люди должны использовать outDir + .d.ts + .js .

Опять же, по этим интересным причинам, если вы отправляете файлы .ts + .js , происходят следующие неприятности:

  • Если ваш пакет используется в nodejs кем-то, использующим outDir , ваш пакет мешает другим людям outDir .
  • По мере реализации новых более строгих параметров компилятора TypeScript они не могут использоваться людьми, использующими ваш пакет, если вы не обновите свой пакет для компиляции с этими параметрами.

Требуется помощь: rose:

Мы можем предоставить _дополнительное_ сообщение об ошибке, если путь содержит node_modules котором говорится:

Поскольку файл находится в node_modules вам не нужно перекомпилировать файлы .ts в node_modules и вам следует связаться с автором пакета, чтобы попросить их использовать --declaration --outDir . Подробнее https://github.com/TypeStrong/ts-loader/issues/278

Спасибо за расследование и напишите на @basarat. То, что вы сказали, имеет смысл. Мне нравится идея сообщения об ошибке, которое вы предлагаете. Было бы просто реализовать?

Было бы просто реализовать?

С https://github.com/TypeStrong/ts-loader/blob/a438869c2a6ac97d176af4e5aac268838d4a3350/src/index.ts#L34 -L36

    if (outputText === null || outputText === undefined) {
        throw new Error(`Typescript emitted no output for ${filePath}`);
    }

К :

    if (outputText === null || outputText === undefined) {
        const additionalGuidance = filePath.indexOf('node_modules') !== -1 
        ? "You should not need to recompile .ts files in node_modules and should contact the package author to request them to use --declaration --outDir. More https://github.com/TypeStrong/ts-loader/issues/278"
        : "";
        throw new Error(`Typescript emitted no output for ${filePath}.${additionalGuidance}`);
    }

Конечно, это непроверенный код, и дьявол будет в деталях + добавление теста, аналогичного https://github.com/TypeStrong/ts-loader/pull/365 : rose:

FWIW, возможно, стоит превратить ваши выводы в сообщение в блоге (если вы так настроены). Когда дело доходит до хорошей практики, всегда есть идея, и кажется, что это все еще новая территория. Есть ли у вас какие-нибудь идеи, опубликовала ли команда TypeScript какие-либо мысли по этому поводу?

Не могу перестать думать об этом:

Немного переиграли, уверен: smile:

Извините, я все еще не понял суть проблемы, просто прочитав: разочарован:

Проблема в том, что «если автор библиотеки отправляет .ts в пакете npm, ts-loader не может скомпилировать его в node_modules». Это правильно?

@HerringtonDarkholme, да, это верно. Теперь есть предупреждение, когда это происходит

Кстати, я столкнулся с этой проблемой на Mac. Все работает нормально на компьютере с Windows, но на компьютере Mac начинается ад.

Не уверен, актуально ли это. Но подход https://github.com/laco0416/light-ts-loader весьма интересен. Он пропускает все проверки типов во время сборки. (Проверка выполняется в редакторе или отдельном вызове tsc).

Может быть, вы можете попробовать флаг transpileOnly в ts-loader.

@basarat Спасибо!

Я выдергивал волосы, пытаясь заставить это работать. Я думал, что чистый .ts был бы замечательным, но он не поддерживается командой Typescript (что имеет смысл, потому что как кто-то будет использовать вашу библиотеку).

Но все, что мне нужно было сделать, это то, что вы сказали, и все работает:

  • В tsconfig.ts:

    • Установить outDir: ‘lib’
    • Определение набора: истина
  • В операторах импорта:

    • Добавьте / lib в конец:
      • @ сказал / платформа
      • @ сказал / платформа / библиотека

Спасибо!

К сожалению, доставка файлов js / d.ts не является для меня решением. У меня 2 приватных репозитория:

  • project-web
  • project-common

Оба репозитория написаны на Typescript.
project-web зависит от project-common поэтому я решил получить репозиторий project-common github с помощью npm и просто сделать что-то вроде этого в project-web :

import { CommonComponents } from 'project-common'

Проблема в том, что я не могу предоставить предварительно скомпилированные js / d.ts (в основном из-за встраивания файлов sass в файлы ts, которые обрабатываются веб-пакетом, например: { styles: [require('sample.sass')] } поэтому мне нужно связать / скомпилировать два чистых репозитория TS вместе в один файл пакета (один из node_modules). Конечно, возникает ошибка. Самое смешное, что это происходит случайно .. Какие-нибудь решения?

ERROR in ../~/project-common/index.ts
Module build failed: Error: Typescript emitted no output for /Users/kpudlik/project-web/node_modules/project-common/index.ts
    at Object.loader (/Users/kpudlik/project-web/node_modules/ts-loader/index.js:458:15)
 @ ./app/app.module.ts 3:26-54

@basarat

Что я сделал, чтобы не включать «/ lib» в операторы импорта, так это создать файл index.js, который экспортирует библиотеку в качестве основной точки входа:

index.ts:

export * from './lib'

Это нормально для меня, если мне не нужен конкретный файл, но это не страшное неудобство как есть.

Я не использовал набор текста для своих собственных проектов, но если у меня возникнут проблемы, я изучу это.

То, что я сделал, чтобы мне не нужно было включать «/ lib» в операторы импорта, — это сделать index.js

Вместо этого вы можете просто изменить свой main в package.json чтобы он указывал на файл в папке lib : rose:

@basarat

Если ваш пакет используется в nodejs кем-то, кто использует outDir, ваш пакет испортит опцию outDir другим людям.

Для пакета NPM, если мы отправляем файлы js в tsconfig.json outDir (например, dist/ или build/ ) и отправляем файлы ts в src , это все равно испортит опцию outDir других людей? (Надеюсь нет.)

Для пакета NPM, если мы отправим файлы js в outDir tsconfig.json (например, dist / или build /) и отправим файлы ts в src, будет ли это все равно испортить опцию outDir других людей? (Надеюсь нет.)

Нет. Не забудьте добавить typings path к package.json : rose:

Я часто использую такую ​​структуру для упорядочивания исходного кода:

proj/
  package.json
  node_modules/ <- external deps
  src/
    node_modules/ <- my code
      client/
      server/
      shared/

Это позволяет мне использовать, например, import * as api from 'shared/api' вместо использования относительных путей. К сожалению, это вызывает ложное срабатывание для этого сообщения об ошибке, потому что ts-loader видит node_modules в имени пути и предполагает, что я компилирую файлы .ts из моих deps. : /

Есть ли способ исправить это через конфигурацию проекта или апстрим-патч? Это меня убивает, Смоллс!

Изменить: я должен отметить, что этот шаблон отлично работает с tsc , но не с webpack + ts-loader .

Привет @AndyBarron!

Думаю, вас укусило это: https://github.com/TypeStrong/ts-loader/blob/master/src/index.ts#L38

Если вы скомпилируете свою версию ts-loader без проверки, все ли у вас нормально работает?

Я должен сказать, что, хотя я понимаю желание избежать ада относительных путей (парень, это съедает мое время, пытаясь проложить наши правильные пути), я бы не решился использовать ваш подход. 😄

Я попробую и вернусь к вам.

Если есть лучшее решение, я его еще не слышал 😛

Да — я чувствую твою боль

У меня так много проблем по этому поводу, что мне интересно, можно ли включить такое поведение за флагом согласия.

Я здесь в одной лодке. У нас есть общий модуль, который импортируется нашим основным модулем, и мы хотели бы импортировать файлы ts из общего модуля.

Хорошо — если кто-то хочет составить PR, который позволяет это, я с радостью посмотрю.

Идеальная реализация:

  • Новый allowTsInNodeModules варианта для TS-загрузчика , что если true не выполняют проверку , что приводит к метанию You should not need to recompile .ts files in node_modules сообщения здесь
  • Добавьте суффикс к существующему сообщению You should not need to recompile .ts files in node_modules... с советом о том, как его использовать. Что-нибудь подходящее «предупреждение-у» вроде But if you really want to do this; use the allowTsInNodeModules option

Не беспокойтесь об исправлении тестов; Я могу помочь с этим.

У меня такая же проблема с Typescript 3.2.2 и ts-loader 5.3.1. Как ни странно, в одном из моих проектов он работает, а в другом не работает.

Я тоже сталкиваюсь с этой проблемой, но нечасто. Иногда это работает, иногда нет.

yarn start build
...
Done in 12.65s.

При повторной попытке построить:

yarn start build
...
ERROR in ./node_modules/t-systems-aurelia-components/src/value-converters/date-format-value-converter.ts
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for xxxnode_modulest-systems-aurelia-componentssrcvalue-convertersdate-format-value-converter.ts.
    at makeSourceMapAndFinish xxxnode_modulests-loaderdistindex.js:78:15)
    at successLoader (xxxnode_modulests-loaderdistindex.js:68:9)
    at Object.loader (xxxnode_modulests-loaderdistindex.js:22:12)
 @ ./src/main.ts
 @ ./node_modules/aurelia-webpack-plugin/runtime/empty-entry.js
 @ multi aurelia-webpack-plugin/runtime/empty-entry aurelia-webpack-plugin/runtime/pal-loader-entry aurelia-bootstrapper
...
error Command failed with exit code 2.

В webpack.config.js

{test: /.ts$/, loader: "ts-loader", options: { allowTsInNodeModules: true }},

Изменить: я исправил это, добавив источники пакета в мой tsconfig.json:

"include": [
    "./src/**/*.ts",
    "./node_modules/t-systems-aurelia-components/src/**/*.ts"
  ],

Я считаю, что столкнулся с этим после реструктуризации проекта с рабочими пространствами lerna + yarn.
Сначала я получаю эту ошибку:

ERROR in ~/directory/node_modules/@monorepo/shared/src/security.ts
Module build failed (from ~/directory/node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for ~/directory/node_modules/@monorepo/shared/src/security.ts. By default, ts-loader will not compile .ts files in node_modules.
You should not need to recompile .ts files there, but if you really want to, use the allowTsInNodeModules option.
See: https://github.com/Microsoft/TypeScript/issues/12358
    at makeSourceMapAndFinish (~/directory/node_modules/ts-loader/dist/index.js:78:15)
    at successLoader (~/directory/node_modules/ts-loader/dist/index.js:68:9)
    at Object.loader (~/directory/node_modules/ts-loader/dist/index.js:22:12)
 @ ~/directory/node_modules/@monorepo/shared/src/index.ts 76:9-30
 @ ./src/app/index.js
 @ multi ./src/app/index.js

а затем, когда я добавлю указанный флаг, что-то вроде:

{
  // rest of config...
  module: {
    rules: [
      {
        test: /.[jt]sx?$/,
        loader: 'ts-loader',
        options: {
          allowTsInNodeModules: true,
        },
        exclude: /node_modules(([email protected]).)*$/,
        include: /node_modules/@monorepo/|src//,
      },
    ]
  }
}

Вернемся к сообщению вроде:

ERROR in ~/directory/node_modules/@monorepo/shared/src/security.ts.
Module build failed (from ~/directory/node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for ~/directory/node_modules/@monorepo/shared/src/security.ts.
    at makeSourceMapAndFinish (~/directory/node_modules/ts-loader/dist/index.js:78:15)
    at successLoader (~/directory/node_modules/ts-loader/dist/index.js:68:9)
    at Object.loader (~/directory/node_modules/ts-loader/dist/index.js:22:12)
 @ ~/directory/node_modules/@monorepo/shared/src/index.ts 79:9-36
 @ ./src/app/index.js
 @ multi ./src/app/index.js

Сейчас нужно двигаться дальше, но посмотрю, смогу ли я в ближайшее время сделать репо с минимальным репро.

Доброго времени суток дорогие машинописцы. Проблема не в ts-loader, а в том, что по умолчанию tsc исключает папку node_modules (https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). У них есть плохой пример, показывающий, как исключить файлы с «node_modules» в нем, что приводит к путанице. Я возражал против этого.

В любом случае, чтобы позволить ts-loader использовать исходные файлы машинописного текста непосредственно из node_modules: отредактируйте tsconfig.json и добавьте туда все необходимые пакеты. Например:

_tsconfig.json_

{
"compilerOptions": { },
"include": [
   "node_modules/@company", // all modules bellow from the company will be available
   "node_modules/@company/module", // specific module from the company
    "node_modules/module" // specific module
  ]
}

Другой вариант, который также сработал в моем случае, — установить для параметра ts-loader transpileOnly значение true.

@ritmos да, для меня проблемой

Похоже, что в # 773 это исправлено — можно ли закрыть это, или есть какие-то дополнительные проблемы?

Думаю, ты прав — закрыто.

Была ли эта страница полезной?

0 / 5 — 0 рейтинги

how do I enable generaotrs in tsconfig so when I use async / await in 2.1.1 so my code will take advantage of generators and thus create a lot less trasnpiled code (I am only targeting latest browsers) ?

I thought this will do it

 "lib": [
    "dom",
    "es5",
    "es2015.promise"
  ],

but still I dont see it taking advantage of generators

  "lib": [
    "dom",
    "es5",
    "es2015.promise",
    "es2015.generator"
  ],

  "lib": [
    "dom",
    "es5",
    "es2015.promise",
    "es2015.generator",
    "es2015.core",
    "es2015.collection",
    "es2015.iterable",
    "es2015.promise",
    "es2015.proxy",
    "es2015.reflect",
    "es2015.generator",
    "es2015.symbol",
    "es2015.symbol.wellknown"

@born2net you have to target es6

the "lib" property is just for type declarations from those libs, it doesn’t change what’s output

anyone know how I can make something like this work:

interface Foo<T> {
    (): Bar<T>
    fun (bar: Bar<T>): void
}

function create<T>() {
    return new Bar<T>()
}

function fun<T> (bar: Bar<T>) {
    // ...
}

const f: any = create
f.fun = fun

export default f as Foo<???>

How can I export f so it matches Foo<T>

so I can import Foo elsewhere and use it like Foo<T>()

shouldn’t you just export Foo?

I want to export a function that has some other function properties on it

like:

export default interface Foo<T> {
    (): Bar<T>
    fun (bar: Bar<T>): void
}

that only exports the type; it’s not callable

it seems first of all you should make the fun function generic

function fun<T>(bar: Bar<T>){
}

ahh ok, instead doing:

const f: any = create

you should do:

const f: Foo = create

Foo is generic, needs a type

I think you don’t need the create function

const f: Foo<T> = function <T>() {
    return new Bar<T>()
}

that needs a type for T :(

I want to be able to use this in modules like so:

const b = Foo<number>()
Foo.fun(b)

what about:

function <T>f() {
    return new Bar<T>()
}

I can’t cast that to Foo<T> for the export


export interface Foo<T> {
    (): Bar<T>
    fun (bar: Bar<T>): void
}

export class Bar<T>{

}


function fun<T> (bar: Bar<T>) {
    // ...
}

export function create<T>() {
    return new Bar<T>()
}

function getCreate<T>(): Foo<T>{
    var tmp = create as any;
    tmp.fun = fun;
    return tmp;
}


export default  getCreate()

weird, it seems to lose the generic… thinks the generic type is {}

Does foo really need to be generic?

or can you just make each member generic?

like ….

export interface Foo {
    <T>(): Bar<T>
    fun<T> (bar: Bar<T>): void
}

Yeah, I wanted it to be generic

but it just doens’t make sense unless you are returning a separate instance of the function each time

godammit I was doing it wrong lol

@dtabuenc thanks! Damn, I should’ve known that.

@dtabuenc hi, tx for the answer, sorry I did not mention, I’d like to stay with es5 as target and just add what I need to, to make async/await work… tx again

I thought adding promise and generators in the tsconfig would do the ticks, but I still see the tsc is not taking advantage of generators which are available in my chrome browser (i.e. I get the long format transpliations)

is there any way to get more information about an error message?:

ERROR in ./lib/client/ts/venue_dashboard/factories/DeleteFactory.ts
Module build failed: Error: Typescript emitted no output for /path-to-project/lib/client/ts/venue_dashboard/factories/DeleteFactory.ts
    at Object.loader (/Users/me/api-server/node_modules/ts-loader/dist/index.js:27:15)
 @ ./lib/client/ts/venue_dashboard/factories/index.ts 2:22-48
 @ ./lib/client/ts/venue_dashboard/index.ts
 @ ./lib/client/ts/index.ts

@varunjayaraman try to compile it directly with tscand see if you get any errors

also posted the question in more details here

I don’t think you can target es5 and still have it use generators

@dtabuenc these are the only errors i get:

node_modules/moment/moment.d.ts(251,28): error TS1110: Type expected.
node_modules/moment/moment.d.ts(256,24): error TS1110: Type expected.
node_modules/moment/moment.d.ts(392,98): error TS1110: Type expected.
node_modules/moment/moment.d.ts(393,88): error TS1110: Type expected.
node_modules/moment/moment.d.ts(635,80): error TS1110: Type expected.
node_modules/moment/moment.d.ts(687,84): error TS1110: Type expected.
node_modules/moment/moment.d.ts(688,84): error TS1110: Type expected.
lib/client/custom.typings.d.ts(1,25): error TS1005: '{' expected.

in the newest code though the code that is generated should only be generated once in a lib

yeah @born2net async/await targets es6. i think typescript 2.1 can but don’t hold me to that

typescript 2.1 can target es5*

@varunjayaraman yeah but you are saying target es5 but use native generators.

I don’t think that combination is possible

there is no flag to turn individual poly-fill generation on/off that I know of

oh i thought typescript transpiled down to using a state machine

anyway, so i’m not sure why those errors i get from webpack dont show up in tsc

this is my webpack config, am i doing something wrong?

'use strict';
const path = require('path');
const rootDir = __dirname;

module.exports = {
  entry: path.resolve(rootDir, './lib/client/typescript/index.ts'),
  output: {
    path: path.resolve(rootDir, 'dist/client'),
    filename: 'index.js'
  },
  resolve: {
    extensions: ['.ts', '.jade', '.styl']
  },
  module: {
    rules: [
      {
        test: /.ts$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              configFileName: path.resolve(rootDir, 'tsconfig.client.json')
            }
          }
        ],
        include: [path.resolve(rootDir, 'lib/client/typescript')]
      },
      {
        test: /.jade$/,
        use: ['raw-loader', 'pug-ng-html-loader']
      },
      // {
      //   test: /.styl$/,
      //   use: [
      //     'raw-loader',
      //     'stylus-loader'
      //   ]
      // },
    ]
  }
};

a bunch of my angular 1.x components use the pug ng html loader, i wonder if tat’s what causing the issues

no the error is coming from ts-loader

and you have errors when compiling with tsc

so try to fix it so tsc has no errors

so i changed the name of my typings to just typings.d.ts

and i have this one line:

declare module 'commafy';

not sure why it’s saying { expected

lib/client/typings.d.ts(1,25): error TS1005: '{' expected.

ah ok i fixed it with declare module commafy { }, but still not sure why moment is causing issues

latest version of moment comes pre packaged with typings

@varunjayaraman you are using commonjs module type?

do you mean when i import it, or in my tsconfig

i import it as import * as moment from 'moment'

i import all NPM dependencies that way

is that not best practice?

yeah that’s fine.. I’m assuming then you have commonjs in your tscofnig right?

(and yes in my tsconfig i use commonjs module type)

what’s your typescript version?

I don’t know why you are getting the error about the {

i think you cant do declare module 'commafy'

you have to do declare module nameOfModule { }

no it’s common to do a string-based one like that

for shimming commonjs modules for which you don’t have typings

I have a lot of those in my project so I know it works

i forgot to do $(npm bin)/tsc --project tsconfig.client.json

i think my global tsc is an earlier version

does it compile with no errors now?

only with a bunch of errors in the mongodb.d.ts file

do i need a core-js typings

or something to shim Promises

i use mongoose in the browser ( as a validator), so i wonder if that’s it

no should just set lib to es6

hm, what’s theneed for dom

does that auto insert typings for global DOM objects

all the browser related things

so if you are targetting browser usually you want dom in libs

it has the interface for Window for example

so yeah tsc works but webpack still has a bunch of errors

same errors? about typescript not generating output?

hmm I’m not sure I haven’t used ts-loader

I’ve only used awesome-typescript-loader

does it have verbose errors?

looks like there are options to increase log level

meh, they just give me the same errors lol

so i’ve got another question

i’ve authored an NPM dependency called common that we share between our repos

there’s no type declarations in that repo

everything is a commonjs export

so common is not written in typesctipr?

i’m gonna migrate it to ts after i get this repo working with ts

or can i still do import * as Schema from 'common/dist/schemas/theSchema'

just define the module in your d.ts

and then you can use the import

i only access files from paths within common though, will it still work

like i never do import * as common from ‘common’

it’s always import * as Schema from ‘common/dist/schemas/theSchema’

i do it that way because there are some server-side configs that i don’t want to expose to the client by requiring in common as a whole

so declare it with the path you are using and it will work

Schema will be type any though

You can also define interfaces in it

declare module 'common/dist/schemas/theSchema' {
    interface Schema {
    }

    const placeHolder: Schema;
    export = placeHolder;
}

if youw ant to start filling in schema

if you do that then the interface of Schema in import * as Schema from 'common/dist/schemas/theSchema' will be Schema

so i’m getting some weird issues with your solution @dtabuenc . I tried declaring a module declare module 'common/dist/virtuals/Venue', but then when i import * as VenueHelpers from 'common/dist/virtuals/Venue' it gives me this error: Module not found: Error: Can't resolve 'common/dist/virtuals/Venue'

(the file for sure exists)

where are you putting your declare module?

and how are you including that .d.ts file into your compilation context?

is it added to your tsconfig or loaded with ///<refrence/>?

in my tsconfig.client.json i have "include: ["lib/client/*"]"

then it should totally work

unles youa re mis-spelling or something or not using 2.0+

i rimraffed my node_modules and im re yarn installing right now

the file must not be getting loaded
try just referencing it

in the file you are doing the import

just to see if that works

///<reference path="path/to/your/d.ts" />

and it’s relative to that file or to the tsconfig.json

something must be wrong with my webpack config

try all compiles in tsc first to eliminate any webpack weirdness

yeah tsc cant find it either

is there something off with my config?

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noImplicitAny": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": "node",
    "removeComments": true,
    "sourceMap": true,
    "noEmitOnError": true,
    "lib": ["es6", "dom"]
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "lib/client/typescript/*"
  ]
}

nothing jumps out at me
although noEmitOnError is probably why you were getting that «typescript emitted no output» from tsloader

But in certain situation like method call, we can nudge the compiler to do more inference! Very useful finding! I want to thank @aluanhaddad here!

i keep getting an error: Class 'UserSt' incorrectly extends base class 'StateS'.
Types have separate declarations of a private property 'mh'.

can someone tell me what is different?

@Injectable()
export class StateS {
  state;

  constructor(private mh: ResMsgHandlerS) {
    this.state = new BehaviorSubject({});
  }
}

@Injectable()
export class UserSt extends StateS {
  constructor(private userS: UserS, private mh: ResMsgHandlerS) {
    super(mh);
  }
}

I think you actually want to use protected

Hi!

export function createMuiTheme(config = {} as any) {

  const {
    palette = createPalette(),
    breakpoints = createBreakpoints(),
    mixins = createMixins(breakpoints),
    typography = createTypography(palette),
    ...more
  } = config as any;

...
}

why typescript erroring this?
Error:(17, 27) TS2448:Block-scoped variable 'breakpoints' used before its declaration.

not find module.png

I’m facing first time. should i need to configure something else?

@dtabuenc no, should I install?

I’ve been able to generate *.d.ts and *.js from my *.ts source files. I need to assembly those files in order to create an npm package. What do I need to do from now on?

@Truedrog I think this is a TS bug. Could you file it in TypeScript issue?

anyone knows how can I add typescript snippets in vs code?

e.g for loop snippet etc…

anyone how why i’m getting weird typescript compilation errors relating to node_modules for my client-side typescript compilation?

ERROR in ./~/mongoose/lib/document.js
Module not found: Error: Can't resolve './types/array' in '/path/to/project/node_modules/mongoose/lib'
 @ ./~/mongoose/lib/document.js 823:38-62
 @ ./~/mongoose/lib/document_provider.js
 @ ./~/mongoose/lib/browser.js
 @ ./lib/client/typescript/directives/organizationAddress.ts
 @ ./lib/client/typescript/directives.ts
 @ ./lib/client/typescript/index.ts

i tried excluding node_modules in my config:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noImplicitAny": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": "node",
    "removeComments": true,
    "sourceMap": true,
    "lib": ["es6", "dom"]
  },
  "exclude": ["node_modules"],
  "include": [
    "lib/client/typescript/**/*"
  ]
}

somehow organizationAddress is including the js?

was i kept doing import * as mongoose from 'mongoose' in every file i use mongoose

but i think that creates weird behavior in mongoose

that error is a webpack error then right?

have you used mongoose with typescript before?

no
but I don’t think it’s a typescript issue at that point in the process

it’s trying to include «./types/array» what is that:?

so for some reason it’s not finding it

but it doesn’t seem like that has anything to do with typescript

that’s weird though because it certainly exists

these are the imports at the top of node_modules/mongoose/lib.index.js:

var Schema = require('./schema'),
    SchemaType = require('./schematype'),
    VirtualType = require('./virtualtype'),
    STATES = require('./connectionstate'),
    Types = require('./types'),
    Query = require('./query'),
    Model = require('./model'),
    Document = require('./document'),
    utils = require('./utils'),
    format = utils.toCollectionName,
    pkg = require('../package.json');

hm, does typescript complain about module.exports = exports = MongooseArray;

sorry not typescript, webpack

typescript is not complaining

and see what it is trying to do

hm i think mongoose doesn’t play well with webpack

I don’t know why it wouldn’t

Hi, I am having an issue with » document.getElementById(«fileInput»).files[0];». For typescript, it doesn’t exist… I m struggling with that… And can’t find anwser on google. Any Help?

@stefdelec What is your lib set to in tsconfig.json

make sure you have «dom» in there

I am on VS Typescript project

that’s fine.. you still have a tsconfig.json

Can’t see it. Should I create it?

yes you should always have one for configuring the typescript

What do you mean by ‘dom’?

then? (I mean in the ts config)

@stefdelec

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noImplicitAny": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": "node",
    "removeComments": true,
    "sourceMap": true,
    "lib": ["es6", "dom"]
  },
  "exclude": ["node_modules"],
  "include": [
    "lib/client/typescript/**/*"
  ]
}

Still having the exact same issue.

can you post your tsconfig?

«property file does not exist on type HTMLelement

‘{
«compilerOptions»: {
«target»: «es5»,
«module»: «commonjs»,
«noImplicitAny»: false,
«experimentalDecorators»: true,
«emitDecoratorMetadata»: true,
«moduleResolution»: «node»,
«removeComments»: true,
«sourceMap»: true,
«lib»: [«es6», «dom»]
},
«exclude»: [«node_modules»],
«include»: [
«lib/client/typescript/*/«
]
}

(exact copy-paste of your)

the include and exclude properties don’t apply to you probably

i only meant you need the lib property from tsconfig

(it doesn’t matter from where Iam in my project)

how does it not matter? there’s an include property in my tsconfig that tells the typescript compiler which files to transpile…

I deleted it the inclue exclude property. What I mean is on my problem => typing ; i still got the issue.

I said it too quiclky=> I sill got the issue. It is still not working

beside where can I find the documentation about «lib»? It is not on the official Typescript Website?

@stefdelec you can see what values are available for the ‘lib’ compiler option just by typing tsc --help

usually for web projects lib should be set to ["es5", "dom"]

ah @dtabuenc i figured it out finally

why it couldn’t resolve my custom 3rd party deps

in webpack i forgot to include .js as an extension

48 hours debugging for that :(

thanks for all the help though, youre the man

had a question about this…

does the and in that sentence mean then?

the first sentance after Definition and usage

my question specifically is that is there a sequence of events, or is the and a logical and?

I don’t think that distinction matters

it just returns the value and ends execution

or ends execution and returns the value

you can even think of it as happening at the same time «it ends execution by returning a vaule»

lol, just making sure because I saw a distinction recently, which made no sense.

is there a nice shorthand for re-exporting in ts?

in an index.ts file, would be nice to do something like
«`
export from ‘Uniforms’ as ‘Uniforms’

you can re-export like export { Uniforms } from ‘./uniforms’

doesn’t really work nicely though

that grabs a particular exported value from ‘Uniforms’ and re-exports it

but I want to export everything as a namespace

export * as Uniforms from ‘./Uniforms’

export * as Uniforms from ‘./uniforms’

just do export * from "./StringValidator";

idk if you can re-export as a named export

it probably just grabs whatever the named export from the original file exporting the value is

but @dtabuenc can confirm

I’m not sure you can re-export inside of a namespace

you can re-export everything from the other module

TypeScript error: src/Commando/index.ts(3,15): Error TS1149: File name ‘/Users/skane/art/ts-renderer/src/Commando/Uniforms.ts’ differs from already included file name ‘src/Commando/uniforms.ts’ only in casing

or you can rename individual exports

I re-named that file to Uniforms.ts awhile ago

@stevekane search and replace across your files

make sure the casing in imports is consistent

you can do

export {Uniform as SomeOtherName} from 'unifroms'

had a lowercase still lurking

so there’s no way to re-export a whole module as a namespace then?

or at least no short-hand?

i dont think so. You can also just import it and then re-export it manually

if you want to give it a namespace

import * as Uniforms from './Uniforms'

export Uniforms

yeah but then you import just Uniforms

you can’t import {Uniforms.someType} ....

what I showed above does not work at all

you cant just do export Uniforms

read this page, it’ll give you all the different ways you can import and export modules

@stevekane export {Uniforms}

I assume all this is out of TS’s hands as it’s es6 module syntax

sort of, I mean TS follows ECMAScript, but es6 has no re-export functionality

TS’s module system is like ES6’s on steroids

and i think typescript 2 is tree-shaking compatible

ya it’s nbd, what you showed me is just fine

import * as Uniforms from './Uniforms'
import * as Command from './Command'
import * as GLTypes from './GLTypes'

export { Uniforms, Command, GLTypes }

@varunjayaraman are you sure you can’t re-export in es6? I thought it was basically the same

hm, i think you have to manually import then export

i don’t think you can re-export like export { Blah } from ‘./blah’;

Guys I am facing some problem, hopefully someone can point me in right direction..

I have typescript class with some public, private methods.. I am using this keyword to use some of the private methods defined inside this class from another public methods of same class

but this is ‘undefined’

can you post the function where you’re calling it?

it’s likely a call-back context-loss issue

paste the class def and calling-code

typescript page says, it will happen if I use strict Mode..

are you using fat arrow syntax?

otherwise you’re going to lose context inside the function

can you post the function where you call the private method

‘use strict’;
import { LoginService } from «./login.service»;

export class LoginResource {
loginService = new LoginService();

healthcheck(req, res) {
    console.log('Advertisement API Healthcheck Successful');
    return res.status(200).json({ message: 'Login API Healthcheck Successful' });
}

authenticateUser(req, res) {
    console.log(JSON.stringify(req.body));
    res.setHeader("Content-Type", "application/json");
    var resp = this.loginService.authenticateUser(req.body);

    if (!req.body || !req.body.username || !req.body.password) {
        res.status(400).send({ status: 'NOT_OK', 'error': 'bad request' });
    } else {
        if (resp.status === 'OK') {
            res.status(200).send(this.loginService.authenticateUser(req.body));
        } else {
            res.status(404).send(this.loginService.authenticateUser(req.body));
        }
    }
}

}

in this sample.. I have used this.loginService…

this is undefined here… when code is run using node

where is this.loginService set

yeah it is.. i pasted full code…

you never define the class

this is going to be the global context, or in strict mode, it will throw an error

thats what is happening..

what do you suggest varun ?

are you using an ioc container /dependency injection?

like how do you get access to loginService in other parts of your server-side code

ah you didn’t wrap all the code in backticks

i didn’t see above the formatted code

`’use strict’;
import { LoginService } from «./login.service»;

export class LoginResource {
loginService = new LoginService();

healthcheck(req, res) {
    console.log('Advertisement API Healthcheck Successful');
    return res.status(200).json({ message: 'Login API Healthcheck Successful' });
}

authenticateUser(req, res) {
    console.log(JSON.stringify(req.body));
    res.setHeader("Content-Type", "application/json");
    var resp = this.loginService.authenticateUser(req.body);

    if (!req.body || !req.body.username || !req.body.password) {
        res.status(400).send({ status: 'NOT_OK', 'error': 'bad request' });
    } else {
        if (resp.status === 'OK') {
            res.status(200).send(this.loginService.authenticateUser(req.body));
        } else {
            res.status(404).send(this.loginService.authenticateUser(req.body));
        }
    }
}

}`

you have to use 3 backticks

aah crap, sorry using GITTER for first time..

check this… this is my code..

the service is just another class outside, which is exported and injected back

should i use Fat Arrow syntax in these functions ? not sure exactly to use here

@maheshk172 is your error at compile or during running?

are you suing authenticateUser as part of a callback to a promise?

or a callback to anything really?

and if so can you post the line where you do that?

My guess is you are doing smething similar to this:

doSomething.then( loginResource.authenticateUser) ;

if so that won’t work… you need to do something like

doSomething.then( (req, res) => loginResource.authenticateUser(req,res));

this is invoked from another file login.router.ts which is just the router and calls this method on POST request from client..

do you have any example of how to use fat arrow on the methods of class..

Fat Arrow solved the issue..

Понравилась статья? Поделить с друзьями:
  • Error typeerror cannot read properties of undefined reading push
  • Error typeerror cannot read properties of undefined reading normalmodule
  • Error typeerror cannot read properties of undefined reading nativeelement
  • Error typeerror cannot read properties of undefined reading length
  • Error typed files cannot contain reference counted types