Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: auto externals support local external files #2383

Merged
merged 3 commits into from
May 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/umi-plugin-auto-externals/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# umi-plugin-auto-externals

A simple way to external in umi.
A simple way to [external](https://webpack.js.org/configuration/externals/) packages in umi.

## Usage

Expand Down Expand Up @@ -37,6 +37,7 @@ https://github.com/umijs/auto-external-packages
### urlTemplate

* Type: `String`
* Default: `{{ publicPath }}externals/{{ library }}@{{ version }}/{{ path }}`

If you want to use your own CDN service, you need to config this item.

Expand All @@ -49,3 +50,7 @@ For example: `https://unpkg.com/{{ library }}@{{ version }}/{{ path }}`
* Type: `Boolean`

If checkOnline is true, we will check all urls if online.

## LICENSE

MIT
1 change: 1 addition & 0 deletions packages/umi-plugin-auto-externals/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
],
"dependencies": {
"auto-external-packages": "^1.0.0",
"copy-webpack-plugin": "5.0.3",
"semver": "6.0.0",
"urllib": "2.33.3"
},
Expand Down
63 changes: 57 additions & 6 deletions packages/umi-plugin-auto-externals/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { IApi } from 'umi-types';
import { join } from 'path';
import { join, dirname } from 'path';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import { existsSync } from 'fs';
import assert from 'assert';
import { IOpts } from './types';
import { getExternalData, onlineCheck } from './util';

const PATH_KEY = 'externals';

export default function(
api: IApi,
{
packages = [],
urlTemplate = 'https://unpkg.com/{{ library }}@{{ version }}/{{ path }}',
urlTemplate = `{{ publicPath }}${PATH_KEY}/{{ library }}@{{ version }}/{{ path }}`,
checkOnline = false,
}: IOpts,
) {
Expand All @@ -18,6 +23,7 @@ export default function(
config,
packages,
urlTemplate,
publicPath: config.publicPath || '/',
});

debug('User external data:');
Expand Down Expand Up @@ -50,16 +56,61 @@ export default function(
(accumulator, current) => accumulator.concat(current.styles),
[],
);
api.addHTMLLink(() =>
styles.map(href => ({
api.addHTMLLink(() => {
return styles.map(href => ({
rel: 'stylesheet',
href,
})),
);
}));
});

// 如果 urlTemplate 不是 cdn,输出到 dist 目录下
api.modifyWebpackConfig(webpackConfig => {
const { cwd } = api;
if (!/^https?:\/\//.test(urlTemplate)) {
// TODO: 不和前面的 urlTemplate 有耦合
assert(
urlTemplate.includes('{{ library }}@{{ version }}'),
`urlTemplate config should includes {{ library }}@{{ version }}`,
);
const copyConfig = scripts.concat(styles).map(path => {
const [nameVersion, ...relPathArr] = path
.split(`${PATH_KEY}/`)[1]
.split('/');
const relPath = relPathArr.join('/');
const [name] = nameVersion.split('@');
return {
from: getRealPath({
name,
relPath,
alias: webpackConfig.resolve.alias,
cwd,
}),
to: dirname(join(webpackConfig.output.path, path)),
};
});

webpackConfig.plugins.push(new CopyWebpackPlugin(copyConfig));
}
return webpackConfig;
});

// TODO: 传递 exclude
}

function getRealPath({ name, relPath, alias, cwd }) {
let realPath = null;
if (alias[name]) {
realPath = join(alias[name], relPath);
} else {
realPath = join(cwd, 'node_modules', name, relPath);
}
assert(
existsSync(realPath),
`Copy to output path failed: ${realPath} not exists`,
);
return realPath;
}

function getWebpackExternalConfig(configs) {
const res = [];
const objectConfig = {};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ interface IGetExternalDataParams {
packages: string[] | Boolean;
config: IConfig;
urlTemplate?: string;
publicPath?: string;
}

function packagesToArray(packages: string[] | Boolean): string[] {
Expand Down Expand Up @@ -99,13 +100,15 @@ function renderUrls({
isDevelopment = false,
urlTemplate = '',
version = '',
publicPath = '/',
}) {
const targetUrls = isDevelopment ? urls.development : urls.production;
return (targetUrls || []).map(path => {
const model = {
library: dependencie,
path,
version,
publicPath,
};
return urlTemplate.replace(/{{ (\w+) }}/g, (str, key) => model[key] || str);
});
Expand All @@ -116,6 +119,7 @@ function getConfigItem({
urlTemplate,
version,
isDevelopment,
publicPath,
}): IExternalData {
const {
key,
Expand All @@ -130,6 +134,7 @@ function getConfigItem({
isDevelopment,
urlTemplate,
version,
publicPath,
};

const [
Expand All @@ -153,7 +158,7 @@ function getConfigItem({
function getExternalData(args: IGetExternalDataParams): IExternalData[] {
configValidate(args);

const { pkg, versionInfos, packages, urlTemplate } = args;
const { pkg, versionInfos, packages, urlTemplate, publicPath } = args;
const isDevelopment = process.env.NODE_ENV === 'development';
const externalDependencies = packagesToArray(packages);
const allExternalVersions = getAllKeyVersions(
Expand All @@ -168,6 +173,7 @@ function getExternalData(args: IGetExternalDataParams): IExternalData[] {
urlTemplate,
version: allExternalVersions[key],
isDevelopment,
publicPath,
}),
);
}
Expand Down
7 changes: 6 additions & 1 deletion packages/umi-plugin-auto-externals/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ import error from './error';
async function onlineCheck(configs) {
let urls = [];
(configs || []).forEach(({ scripts, styles }) => {
urls = urls.concat(scripts).concat(styles);
urls = urls
.concat(scripts)
.concat(styles)
.filter(url => {
return /^https?:\/\//.test(url);
});
});
if (!urls.length) {
return;
Expand Down
Loading