Reputation: 1056
I've followed various tutorials to try and get my existing app working with Typescript. It's now running fine when working in dev mode: cross-env NODE_ENV=development ts-node-script ./server/index.js
When I run next build
it succeeds, but once I try to run ./server/index.js
I get the error: code: 'MODULE_NOT_FOUND',
I also don't see any compiled version of the .ts
file in .next/
or something. The instructions here make it seem like next build
just handles everything...
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"],
"ts-node": {
"esm": true,
"compilerOptions": {
"module": "commonjs" // you can also override compilerOptions. Only ts-node will use these overrides
}
}
}
next.config.js
const { parsed: localEnv } = require("dotenv").config();
const webpack = require("webpack");
const apiKey = JSON.stringify(process.env.API_KEY);
const hostUrl = JSON.stringify(process.env.HOST);
module.exports = {
webpack: (config) => {
const env = { API_KEY: apiKey, HOST_URL: hostUrl };
config.plugins.push(new webpack.DefinePlugin(env));
// Add ESM support for .mjs files in webpack 4
config.module.rules.push({
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto",
});
return config;
},
};
Upvotes: 2
Views: 888
Reputation: 1056
You (past me) need to build the files with tsc
as part of the existing build command.
If you run into issues with the files not being output (just an empty dist
directory) you'll need a different tsconfig.json
for production.
Then update your package.json scripts:
"build": "next build; tsc --project tsconfig.server.json",
"start": "node start dist/index.js"
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "dist",
"noEmit": false
},
"include": ["server"]
}
Upvotes: 2