[英]Using Webpack to turn TypeScript into es5
我創建了一個非常簡單的環境來試驗 TypeScript 和 Webpack。 我盡可能地遵循在線示例,但構建的輸出包含() =>
,它應該已更改為 ES5 語法。 請注意,我沒有使用 Babel - 據我所知,TypeScript 應該能夠在沒有它的情況下生成 ES5。
這是我的 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"
},
這是我的 tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "es2020",
"target": "ES5",
"allowJs": true
}
}
這是 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'),
},
};
這是 src/index.ts:
export const myObj = {
visual: "the visual",
audio: "the audio"
}
在執行npm run build
我在 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)})();
請注意,即使我指定了“ES5”,代碼也不會在舊瀏覽器上運行。
文件夾結構為:
dist
my-library.js
src
index.ts
package.json
tsconfig.json
webpack.config.js
我錯過了什么? 謝謝。
您可能正在使用webpack5
,它引入了對 es6+ 的支持作為target
。 您看到的代碼是 Webpack 生成的代碼(它是運行時代碼),您可以指定它應該使用es5
。
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
target: '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'),
},
};
有關更多選項,請查看文檔
如果您使用的是 Webpack 5,文檔說明:
module.exports = {
// ...
target: ['web', 'es5'],
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.