我遵循了打字稿指南:https : //webpack.js.org/guides/typescript/ 當我以“生產”模式運行 webpack 時,它幾乎沒有發出任何內容。
這是我的 src/index.ts 檔案的源代碼:
export function foo() {
return 'foo'
}
export const bar = 'bar'
然后我運行命令:
webpack
我將“bundle.js”檔案編譯到“dist”檔案夾中,代碼為:
(()=>{"use strict"})();
但是,如果轉到 'src' 檔案夾并使用 'tsc' 命令進行編譯,則會生成具有以下代碼的 javascript 檔案:
"use strict";
exports.__esModule = true;
exports.bar = exports.foo = void 0;
function foo() {
return 'foo';
}
exports.foo = foo;
exports.bar = 'bar';
我認為 'dist/bundle.js' 和 'src/index.js' 檔案應該是一樣的,至少功能是一樣的。但是現在“dist/bundle.js”檔案根本不起作用。
以下是其他相關檔案的代碼:
// package.json
{
"name": "webpack-ts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^9.2.6",
"typescript": "^4.5.2",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1"
}
}
// webpack.config.js
const path = require('path');
module.exports = {
mode: 'production',
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'),
},
};
// tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"moduleResolution": "node"
}
}
誰能幫我?謝謝你。
uj5u.com熱心網友回復:
在productionmode 下使用 webpack將通過tree splash丟棄死代碼。
foo函式和bar變數是未使用的匯出,應該洗掉。這就是所謂的“死代碼”。
如果您創建另一個使用該bar變數的檔案。
import { bar } from "./index";
console.log(bar);
該bundle.js輸出將是:
(()=>{"use strict";console.log("bar")})();
TypeScript 只是擦除型別并將代碼編譯為目標 JavaScript 語言版本,例如es5,它沒有搖樹概念。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/382164.html
標籤:javascript 打字稿 网络包 webpack-5
