From a52ab2ee52743977c422c0b689d829baa906e648 Mon Sep 17 00:00:00 2001 From: jaywcjlove <398188662@qq.com> Date: Mon, 7 Mar 2022 17:19:40 +0800 Subject: [PATCH] fix: Fix ES modules issue. --- core/src/index.ts | 10 ++++++++-- core/src/utils.ts | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/core/src/index.ts b/core/src/index.ts index 336905d..4f13e6a 100644 --- a/core/src/index.ts +++ b/core/src/index.ts @@ -10,7 +10,7 @@ import { overridePaths } from 'kkt/lib/overrides/paths'; import { sync as gzipSize } from 'gzip-size'; import filesize from 'filesize'; import './overrides'; -import { filterPlugins, removeLoaders } from './utils'; +import { filterPlugins, removeLoaders, hasTypeModule } from './utils'; function help() { const { version } = require('../package.json'); @@ -181,6 +181,8 @@ process.on('exit', (code) => { data.cssFilePath = path.resolve(argvs.out, `${fileName}.css`); data.cssMinFilePath = path.resolve(argvs.out, `${fileName}.min.css`); + const isESM = inputFile.endsWith('.mjs') || (!inputFile.endsWith('.cjs') && hasTypeModule(inputFile)); + if (fs.existsSync(data.fileMinPath)) { data.fileMin = fs.readFileSync(data.fileMinPath).toString(); } @@ -226,7 +228,7 @@ process.on('exit', (code) => { conf.mode = scriptName === 'watch' ? 'development' : 'production'; conf.output = {}; if (argvs.external) conf.externals = argvs.external; - conf.output.libraryTarget = 'commonjs'; + conf.output.libraryTarget = 'commonjs2'; conf.output.path = outDir; conf.output.filename = data.filename; if (isWeb) { @@ -234,6 +236,10 @@ process.on('exit', (code) => { if (argvs.library) { conf.output.library = argvs.library; } + } else if (isESM) { + conf.output.libraryTarget = 'module'; + conf.experiments = conf.experiments ? conf.experiments : {}; + conf.experiments.outputModule = true; } return conf; }; diff --git a/core/src/utils.ts b/core/src/utils.ts index 1676b78..3df7cf5 100644 --- a/core/src/utils.ts +++ b/core/src/utils.ts @@ -1,3 +1,6 @@ +import * as PATH from 'path'; +import { readFileSync } from 'fs'; +import fs from 'fs-extra'; import { WebpackConfiguration, MiniCssExtractPlugin } from 'kkt'; import CssMinimizerPlugin from 'css-minimizer-webpack-plugin'; import TerserPlugin from 'terser-webpack-plugin'; @@ -57,3 +60,14 @@ export function removeLoaders(conf: WebpackConfiguration) { }); return conf; } + +export function hasTypeModule(path: string) { + while (path !== (path = PATH.resolve(path, '..'))) { + try { + return fs.readJSONSync(PATH.resolve(path, 'package.json')).type === 'module'; + } catch (e) { + if (e.code === 'ENOENT') continue; + throw e; + } + } +}