什么是“节点方式”跨多个文件分割代码?
问题描述:
我目前正在研究NodeJS/Typescript项目,它是一个带有NodeJS服务器的HTML5客户端,它通过web-sockets进行通信。来自C#背景,我喜欢将我的代码分成不同的文件,包括用于序列化和反序列化的对象的共享文件,用于以有组织的方式发送/接收数据。什么是“节点方式”跨多个文件分割代码?
目前在服务器端,我有编译选项设置为将其编译为单个JavaScript文件,并将其作为我的启动脚本,但我相信这是对我的问题的一个混乱的解决方案。要解决输出文件的顺序问题,我还必须在我的“主”打字稿文件的顶部放置一个引用到各种TypeScript文件的有序列表。
这似乎是完全错误的方式来做到这一点,是否仍然可以分离出不同的Typescript(/ Javascript)文件,以便不同的逻辑区域处于专用位置,同时仍然能够共享文件在我的HTML客户端&我的NodeJS服务器之间,还是这只是一个解决方法,我将不得不学会忍受?
答
您可以使用webpack module bundler来避免您订购的参考文献列表。 Webpack负责所有的依赖关系解析和引用。为了在服务器和客户端之间共享代码,你可以在一个通用的模块/包中分离出来并在两侧导入它。
我使用webpack将我的Typescript代码编译为用于服务器代码的ES6代码,并向浏览器兼容的代码添加了额外的构建步骤(babel.io)。
下面的示例配置显示的WebPack与打字稿用法:
var path = require('path');
module.exports = {
entry: {
app: [ path.join(__dirname, './src/App.ts') ]
},
devtool: 'source-map',
output: {
path: path.join(__dirname, './build'),
filename: 'js/bundle.[name].js'
},
module: {
loaders: [{
// The loader that handles ts and tsx files. These are compiled
// with the ts-loader and the output is then passed through to the
// babel-loader. The babel-loader uses the es2015 and react presets
// in order that jsx and es6 are processed.
test: /\.ts(x?)$/,
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2015!ts-loader'
}, {
// The loader that handles any js files presented alone.
// It passes these to the babel-loader which (again) uses the es2015
// and react presets.
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015']
}
}]
},
resolve: {
extensions: ['', '.ts', '.tsx', '.js'],
modulesDirectories: ['node_modules', 'src', 'lib']
}
};
你试过http://browserify.org/,林不知道如果与打字稿 –
是兼容@ jack.the.ripper我不明白为什么这不应该工作,谢谢领先。 –