2017-06-03 101 views
0

在一個使用Typescript和Webpack的項目中,我想強制通常全局庫(例如jQuery)被視爲UMD全局變量。Webpack + Typescript - 如何將導入的非UMD模塊隔離到一個文件?

現在,如果我在參考$的文件中省略import * as $ from 'jQuery',則webpack會成功,但腳本在運行時會失敗。但是,import * as _ from 'lodash'具有預期的行爲,因爲省略了webpack構建時會失敗。

考慮以下文件:

first.ts

import * as $ from "jquery"; 
import * as _ from "lodash"; 

import { second } from "./second"; 

$(() => { 
    const message = _.identity("first.ts"); 
    $(".first").html(message); 
    second.Test(); 
}); 

second.ts

//import * as $ from "jquery"; 
//import * as _ from "lodash"; 

export const second = { 
    Test:() => { 
     const message = _.identity("second.ts"); 
     $(".second").html(message); 
    } 
} 

的index.html

<html> 
    <head> 
     <script type="text/javascript" src="./bundle.js"> 
     </script> 
    </head> 
<body> 
<div class="first"></div> 
<div class="second"></div> 
</body> 
</html> 

的package.json

{ 
    "name": "webpack-typescript-test", 
    "version": "1.0.0", 
    "description": "", 
    "main": "index.js", 
    "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1" 
    }, 
    "author": "", 
    "license": "ISC", 
    "dependencies": { 
    "@types/jquery": "^2.0.46", 
    "@types/lodash": "^4.14.65", 
    "jquery": "^3.2.1", 
    "lodash": "^4.17.4", 
    "ts-loader": "^2.1.0", 
    "typescript": "^2.3.3", 
    "webpack": "^2.6.1" 
    } 
} 

tsconfig.json

{ 
    "compilerOptions": { 
     "target": "ES5", 
     "sourceMap": true, 
     "module": "commonjs", 
     "types": [] 
    }, 
    "include": [ 
     "./*.ts" 
    ], 
    "exclude": [ 
     "./node_modules" 
    ] 
} 

webpack.config.js

const path = require('path'); 

module.exports = { 
    entry: './first.ts', 
    resolve: { 
     extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'] 
    }, 
    module: { 
     loaders: [ 
      { 
       test: /\.ts$/, 
       loader: 'ts-loader', 
       exclude: /node_modules/ 
      } 
     ] 
    }, 
    output: { 
     filename: 'bundle.js', 
     path: path.resolve(__dirname) 
    } 
} 

有一種可以強制執行所有.ts文件中的導入語句的方法?

回答

1

考慮使用的WebPack配置externals選項: https://webpack.js.org/configuration/externals/

我想它的目的你的用例匹配得很好。

+0

有趣的是,謝謝你的回答。這看起來像它支持像我的用例* * * *;我試圖在'import'語句丟失時引發錯誤 - 我不明白我如何使用'externals'選項來執行此操作。 – cynicaloptimist

相關問題