Issue
I want to configure a blank project with webpack and typesript.
So far this is not going well^^. My entry file (index.ts
) is not recognized.
const path = require('path');
module.export = {
entry: '../src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
This is how the project structure looks like:
Maybe some of you guys can help me out on the configuration. I actually followed the steps from the webpack doc. BTW: If i change index.ts to index.js the bundling works...
Solution
Try this to verify if your webpack setup for typescript works fine.
Below steps are mentioned in webpack docs for typescript , but not with this much precision, so i would recommend you to follow my below steps to have some progress with debugging your issue
Install below dev dependencies
npm install webpack webpack-cli --save-dev
npm install typescript ts-loader --save-dev
Create a sample script to test if ts gets converted into js
./src/index.ts
console.log("in index.ts");
function addNumbers(a: number, b: number) {
return a + b;
}
var sum: number = addNumbers(10,15)
console.log('Sum of the two numbers is: ' +sum);
Create tsconfig.json to compile typescript to es5
./tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}
Create webpack.config.js
./webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
Add below entires to your package.json
./package.json
"scripts": {
"webpack" : "webpack",
"dev" : "npm run webpack -- --mode development",
"prod" : "npm run webpack -- --mode production"
}
Once above steps are done
- Run webpack, in dev or prod mode
npm run dev or npm run prod
- You have to see below output, go into
dist
folder to see the generated js bundle
- Go into
dist
folder and link the generated js bundle to a sample html file sayindex.html
for example - If you run the html file in the browser you would see the js output in browser console
if you get the results as mentioned above then what does it mean?
This means ts to js converstion happens without any issue
You can find above steps in a project in my gitrepo.
i've tested this setup and it works without a problem in my machine
node 8.11.4 npm 5.6.0
.
Answered By - divine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.