2017-08-14 124 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

相關問題