我想将ts文件中的子模块导入到我的项目中。 问题在于输出文件包括整个导入的文件,而不仅包括导入的对象。
我有一个example.ts文件,其中包含多个导出:
export enum e1{a, b}
export enum e2{c, d}
export class exampleclass
{
static f()
{
return 1;
}
}
更新: 我还有另一个文件-exampleUser.ts,它从example.ts导入零件。
import {e2} from "./example";
export enum eu1{a, b}
export enum eu2{c, d}
我有第三个文件-main.ts,它从exampleUser.ts导入零件。 当我使用以下导入
import {eu2} from "./exampleUser";
(并使用webpack)转换项目,捆绑的输出包含exampleUser.ts和example.ts中未使用的代码部分。
tsconfig.json:
{
"compilerOptions": {
"target": "es3",
"module": "es6",
"allowJs": true,
"checkJs": false,
"sourceMap": true,
"removeComments": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
}
}
package.json:
{
"sideEffects": false
"devDependencies": {
"concurrently": "^3.6.0",
"ts-loader": "^4.3.0",
"typescript": "^2.8.3",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3"
},
}
webpack.prod.js:
{
mode: 'production',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
optimization: {
minimize: true, // Control if the output is monified (and uglified) or not
usedExports: true
},
}
package-lock.json:
{
"ts-loader": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-4.3.0.tgz",
"integrity": "sha512-+zduqQJaeouVrGY3y6+nUG7+OE1+Q7slGCHsiQM/aITCEZ0og3GxrJVsnjM5QcWvOcu9C4VR5dP+egIyT+sNNg==",
"dev": true,
"requires": {
"chalk": "2.4.1",
"enhanced-resolve": "4.0.0",
"loader-utils": "1.1.0",
"micromatch": "3.1.10",
"semver": "5.5.0"
}
}
}
是否可以仅导入相关代码?
答案 0 :(得分:0)
您要问的是一棵树在颤抖。 Typescript并非开箱即用。您可以使用webpack做到这一点。请在Tree shaking
中查看如何设置我想设置mode: 'production'
就足够了,webpack将优化您的输出
UPD:
经过一番讨论,我们发现:打字稿的目标低于“ es2015”的类将被编译为常规函数。函数可能通过闭包产生副作用,因此删除“未使用的代码”可能并不安全,并且webpack包含“以防万一”的所有内容
要告诉webpack该函数可以安全删除编译器,可以在函数附近放置#__PURE__
注释,而Typescript放置@class
。
我们可以编写简单的Webpack加载程序,将@class
替换为#__PURE__
。这是一个肮脏但可行的解决方案。
module.exports = function(content) {
return content.replace(/\/\*\* @class \*\//g, '\n /*#__PURE__*/ \n');
};
建议安装的repo
在我的项目中,我更喜欢以下解决方案:打字稿=> ESNext javascript(ts-loader)=> Es5(babel-loader) 这里的打字稿用于类型检查,而babel会注意es5