2017-08-14 120 views
0

处理我的第一个打字稿模块,我希望能够在Apache Cordova应用程序和.Net 4.6 MVC网站(现在)中使用它。经过详尽的阅读后,我得出CommonJS最适合我的需求的结论。然而,我正在努力将模块整合到MVC网站。Typescript Module + Webpack + RequireJS

我用awesome-typescript-loader将我的模块绑定到单个js文件中,然后我使用requirejs将模块加载到MVC站点上。我试图用多种方式导入模块没有成功。

在我的打字稿模块我有一个入口点(index.ts),其中我只导出主类:export * from './src/engine';,和我使用这个类作为的WebPack内我的切入点:

const path = require('path'); 
const webpack = require('webpack'); 
const merge = require('webpack-merge'); 
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin; 

module.exports = (env) => { 
    // Configuration in common to both client-side and server-side bundles 
    const isDevBuild = false; 
    const sharedConfig = { 
     stats: { modules: false }, 
     context: __dirname, 
     resolve: { extensions: ['.ts', '.tsx'] }, 
     output: { 
      filename: '[name].js', 
      publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix 
     }, 
     module: { 
      loaders: [ 
       { 
        test: /\.tsx?$/, 
        loader: 'awesome-typescript-loader' 
       } 
      ] 
     }, 
     plugins: [ 
      new CheckerPlugin() 
     ] 
    }; 

    // Configuration for client-side bundle suitable for running in browsers 
    const clientBundleOutputDir = './dist'; 
    const clientBundleConfig = merge(sharedConfig, { 
     entry: { 'engine': './index.ts' }, 
     output: { path: path.join(__dirname, clientBundleOutputDir) }, 
     plugins: [ 
      new webpack.ContextReplacementPlugin(/moment[\\\/]locale$/, /^\.\/(en)$/) 
     ].concat(isDevBuild ? [ 
      // Plugins that apply in development builds only 
      new webpack.SourceMapDevToolPlugin({ 
       filename: '[file].map', // Remove this line if you prefer inline source maps 
       moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk 
      }) 
     ] : [ 
       // Plugins that apply in production builds only 
       new webpack.optimize.UglifyJsPlugin() 
      ]) 
    }); 

    return [clientBundleConfig]; 
}; 

一旦我有我使用的MVC网站requirejs加载模块所产生的engine.js文件:

<script data-main="/scripts/main" src="~/Scripts/require.js"></script>

main.js

require(['/scripts/compliance-engine.js']); 

最终目标是我可以从javascript调用var compliance = require('compliance-engine');,实例化一个新的引擎实例。

不幸的是,无论我尝试了什么,我都无法完成上述工作(任何时候都不会出现错误,我只是不能在网站上引用该模块)。

回答

1

当使用webpack没有什么是出口,除非你明确地定义它,你应该添加到您的webpack.config.js

output: { 
library: 'MyLibrary' 
libraryTarget: 'var', 
} 

这将会把一个名为窗口MyLibrary变量,它可以从访问你的其他代码。 还有其他选项,以libraryTargetumd/amd等 你可以读到它here

+0

你的先生是一个神,那正是问题!非常感谢 – user3564855

相关问题