我正在構建一個組件庫,並使用Webpack將其捆綁。有些組件只依賴於我編寫的html模板,css和JavaScript,但某些組件需要外部庫。帶有webpack的獨立塊文件
我想實現的是vendor.js
即可選如果您要使用的組件需要它,可以包含此選項。例如,如果用戶只需要一個沒有供應商依賴關係的組件,那麼他們使用main.bundle.js
就足夠了,其中只包含我自己的代碼。
在我index.js
,我有以下的進口:
import { Header } from './components/header/header.component';
import { Logotype } from './components/logotype/logotype.component';
import { Card } from './components/card/card.component';
import { NavigationCard } from './components/navigation-card/navigation-card.component';
import { AbstractComponent } from './components/base/component.abstract';
import { Configuration } from './system.config';
import 'bootstrap-table';
import './scss/base.scss';
所有這些進口的都是我自己的,期待bootstrap-table
。
我已經配置的WebPack是這樣的:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractScss = new ExtractTextPlugin({
filename: "[name].bundle.css"
});
module.exports = {
entry: {
main: './src/index.ts'
},
output: {
path: path.resolve(__dirname, 'dist/release'),
filename: "[name].bundle.js",
chunkFilename: "[name].bundle.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor', // Specify the common bundle's name.
minChunks: function (module) {
// Here I would like to tell Webpack to give
// each bundle the ability to run independently
return module.context && module.context.indexOf('node_modules') >= 0;
}
}),
extractScss
],
devtool: "source-map",
resolve: {
// Add `.ts` as a resolvable extension.
extensions: ['.webpack.js', '.web.js', '.ts', '.js', '.ejs']
},
module: {
rules: [
// All files with a '.ts' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.ts?$/, exclude: /node_modules/, loader: "awesome-typescript-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" },
// Allows for templates in separate ejs files
{test: /\.ejs$/, loader: 'ejs-compiled-loader'},
{
test: /\.scss$/,
use: extractScss.extract({
use: [{
loader: 'css-loader', options: {
sourceMap: true
}
}, {
loader: 'sass-loader', options: {
soureMap: true
}
}]
})}
]
}
}
這將導致兩個.js
文件和一個.css
。但是,webpacks常見的模塊加載功能駐留在vendor.js
中,如果我不首先包含供應商,並且不總是需要,那麼這會導致我的主要不可用。
概括起來講,如果用戶只需要頁腳(沒有外部的依賴關係),這樣就足夠了:
<script src="main.bundle.js"></script>
如果用戶要使用該表,它有一個外部的依賴,他們會需要包括:
<script src="vendor.js"></script>
<script src="main.bundle.js"></script>
眼下,僅包括main.bundle.js
給了我這個錯誤:
Uncaught ReferenceError: webpackJsonp is not defined
。
我知道,我可以用我的供應商大塊在配置的WebPack創建後添加此提取所有常見功能:
new webpack.optimize.CommonsChunkPlugin({
name: 'common'
})
但是這種方法仍然需要用戶包括兩個.js
文件。
我該如何去做到這一點?當我不像上面那樣提取常見模塊時,它似乎只有2kb不等,這對我來說很好。