'Compiling web components with TypeScript and webpack doesn't work
I’m trying to compile my custom element on the browser but im getting this error.
i was able to run this code successfully in storybook but for some reason the same code doesn't work on the browser.
tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "es6",
"rootDir": "./",
"strict": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
webpack.config.js:
const path = require("path");
module.exports = {
mode: "production",
entry: path.resolve(__dirname, "/src/index.ts"),
module: {
rules: [
{
test: /\.ts?$/,
use: "ts-loader",
exclude: /node_modules/,
},
{
test: /\.css$/,
use: "css-loader",
},
],
},
resolve: {
extensions: [".ts", ".js"],
},
output: {
filename: "script.js",
path: path.resolve(__dirname, "public", "static", "bundle"),
},
};
Solution 1:[1]
now its working!
tsconfig.json:
{
"compilerOptions": {
"target": "es6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"module": "es6" /* Specify what module code is generated. */,
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
"strict": true /* Enable all strict type-checking options. */,
"skipLibCheck": true /* Skip type checking all .d.ts files. */,
"moduleResolution": "Node"
}
}
packge.json:
{
"scripts": {
"start": "webpack serve --open",
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1",
},
"keywords": [],
"license": "ISC",
"dependencies": {},
"devDependencies": {
"ts-loader": "^9.2.8",
"typescript": "^4.6.2",
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
}
}
webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/main.ts",
mode: "production",
module: {
rules: [
{
test: /\.ts?$/,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
devServer: {
static: {
directory: path.join(__dirname, "public"),
},
compress: true,
port: 8080,
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "main.js",
},
resolve: {
extensions: [".ts", ".js"],
},
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luís Mestre |

