ts-loader icon indicating copy to clipboard operation
ts-loader copied to clipboard

Export = { } throws an error

Open deryl27 opened this issue 11 years ago • 4 comments

name.ts

export = { "firstname" : "abc" , "lastname" : "def" }

main.ts

import * as details from './name';

I am encountering the following error when webpack bundles the files

Module '"name"' resolves to a non-module entity and cannot be imported using this construct.

deryl27 avatar Aug 06 '15 17:08 deryl27

This is by design (you'll get the same error if you just run tsc). The issue is that you're mixing ES6 module syntax with CommonJS module syntax. You have two options:

// name.ts

export = {
  "firstname" : "abc" ,
  "lastname" : "def"
}

// main.ts

import details = require('./name');

OR

// name.ts

export var firstname = "abc";
export var lastname = "def";

// main.ts

import * as details from './name';

jbrantly avatar Aug 06 '15 17:08 jbrantly

@jbrantly

I was wondering like I have a .json file which I need to import in main.ts. I tried using json-loader but it didnt work for me.

I used a config.ts and tried to import that which resulted into the above error.

Can you suggest me any way of doing it.

deryl27 avatar Aug 06 '15 17:08 deryl27

json-loader is the right way to go. Just keep in mind that in TypeScript when you use the import keyword that means loading a module. That is completely different from loading an asset like JSON or CSS or something, so you don't use the import keyword. See the section of the README on loading assets.

First make sure you've installed json-loader.

// require.d.ts
declare var require: {
    <T>(path: string): T;
    (paths: string[], callback: (...modules: any[]) => void): void;
    ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
};

// name.json

{
  "firstname": "abc",
  "lastname": "def"
}

// main.ts

/// <reference path="require.d.ts" />

var details = require('json!./name.json');

jbrantly avatar Aug 06 '15 17:08 jbrantly

@jbrantly As you have suggested above

var details = require('json!./name.json');

details will not have the raw json. It will be imported as module.exports = { "firstname": "abc", "lastname": "def" }

deryl27 avatar Aug 12 '15 15:08 deryl27