I've created a really simple environment to experiment with TypeScript and Webpack. I've followed online examples as best I could but the output of the build contains () =>
, which should have been changed to ES5 syntax. Note that I'm NOT using Babel - as far as I can tell TypeScript should be able to produce ES5 without it.
Here is part of my package.json:
"devDependencies": {
"ts-loader": "8.0.7",
"typescript": "4.0.3",
"webpack": "5.2.0",
"webpack-cli": "4.1.0",
"webpack-dev-server": "3.11.0"
},
"scripts": {
"build": "webpack"
},
Here is my tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "es2020",
"target": "ES5",
"allowJs": true
}
}
Here is the webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'my-library.js',
path: path.resolve(__dirname, 'dist'),
},
};
Here is src/index.ts:
export const myObj = {
visual: "the visual",
audio: "the audio"
}
After I do npm run build
I get the following in dist/my-library.js:
(()=>{"use strict";var r={607:(r,e,t)=>{}},e={};function t(o){if(e[o])return e[o].exports;var n=e[o]={exports:{}};return r[o](n,n.exports,t),n.exports}t.d=(r,e)=>{for(var o in e)t.o(e,o)&&!t.o(r,o)&&Object.defineProperty(r,o,{enumerable:!0,get:e[o]})},t.o=(r,e)=>Object.prototype.hasOwnProperty.call(r,e),t(607)})();
Notice that the code won't run on old browsers even though I've specified "ES5".
The folder structure is:
dist
my-library.js
src
index.ts
package.json
tsconfig.json
webpack.config.js
What am I missing? Thanks.
You are probably using webpack5
which introduced support for es6+ as the target
.
The code that you see, is the code that Webpack generates (it's runtime code), you can specify that it should use es5
.
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
target: ['web', 'es5']
// ------ ^
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'my-library.js',
path: path.resolve(__dirname, 'dist'),
},
};
For more options checkout the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With