j5juice j5juice - 1 month ago 7
Javascript Question

How to import .js file inside my .tsx file

I am having an issue where webpack is telling me:


ERROR in ./app/app.tsx
(4,25): error TS2307: Cannot find module './sample-data'.


My imports look like this:

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { InboxPane } from './components/Inbox';
import * as Samples from './sample-data';


And lastly this is my sample-data.js file that I am trying to import:

module.exports = {
"humans": {
"John Smith" : {
"conversations": [
{
"who": "bot",
"text": "Hello, can I take your order?",
"time": new Date(2016, 4, 5, 15, 10, 0, 0)
},
{
"who": "human",
"text": "Can I have a small meat-lovers pizza?",
"time": new Date(2016, 4, 5, 15, 10, 30, 0)
},
{
"who": "bot",
"text": "Where would you like it delivered?",
"time": new Date(2016, 4, 5, 15, 11, 0, 0)
},
{
"who": "human",
"text": "123 Sesame Street, Montreal, Canada",
"time": new Date(2016, 4, 5, 15, 11, 30, 0)
},
],
"orders": [
{
"time": new Date(2016, 4, 5, 15, 11, 45, 0),
"pizzas": [{
"toppings": ["Meat-Lovers"],
"size": "S"
}],
"price": 15,
"address": "321 Sesame Street, Montreal, Canada",
"status": "Confirmed" // status := Open -> Confirmed -> In The Oven -> Delivered
}
]
},
"Alan Foster" : {
"conversations": [
{
"who": "bot",
"text": "Hello, can I take your order?",
"time": new Date(2016, 4, 4, 20, 30, 0, 0)
},
{
"who": "human",
"text": "I would like to order an extra-large cheese pizza",
"time": new Date(2016, 4, 4, 20, 30, 15, 0)
},
{
"who": "bot",
"text": "Where would you like it delivered?",
"time": new Date(2016, 4, 4, 20, 30, 30, 0)
},
{
"who": "human",
"text": "123 Sesame Street, Montreal, Canada",
"time": new Date(2016, 4, 4, 20, 30, 45, 0)
},
],
"orders": [
{
"time": new Date(2016, 4, 4, 20, 31, 0, 0),
"pizzas": [{
"toppings": ["cheese"],
"size": "XL"
}],
"price": 15,
"address": "123 Sesame Street, Montreal, Canada",
"status": "Delivered" // status := Open -> Confirmed -> In The Oven -> Delivered
}
]
}
}
};


If I change it to sample-data.ts I get told that it isn't a module. How do I go about getting this loaded into my .tsx file?

Answer

If you want to import the original file without modifications try to set compilerOptions.allowJs to true in your tsconfig.json file:

...
  "compilerOptions": {
    "allowJs": true
...

In case you're ready to modify the file you can turn sample-data.js into sample-data.ts by using the module syntax, like that:

export default {
  "humans": {
    "John Smith" : {
      "conversations": [
        {
          "who": "bot",
          "text": "Hello, can I take your order?",
          "time": new Date(2016, 4, 5, 15, 10, 0, 0)
        },
        {
          "who": "human",
        ...
};

You'll then need to import the file in the following way:

import Samples from './sample-data';

You can read more on TypeScript modules in the official docs. In many cases modules in TypeScript work the same way as in ES2015.

Comments