Craco & Webpack4 & date-fns 项目启动失败报错

212 阅读1分钟

最近项目中碰到 Craco & Webpack4 & date-fns 项目启动失败报错


./node_modules/date-fns/intervalToDuration.mjs
Can't import the named export 'differenceInHours' from non EcmaScript module (only default export is available)

  1. 第一版改动
    "start": "craco start",
    "build": "craco build"
  1. 改动后: 启动成功, build 失败,会报 module 库解析出错
Attempted import error: 'ATN' is not exported from 'antlr4ts/atn/ATN'.

  1. 改动后版本可以
    "start": "parse=true craco start",
    "build": "craco build"
  1. 条件判断添加参加
plugins: [
// 根据传的参数判断
		...(process.env.parse === "true" ? [{
			plugin: require('craco-babel-loader'),
			options: {
				includes: [resolveApp('../shared')],
			},
		}] : []),
	],
  1. 解决 build 和 启动的问题

For those wondering how to do this with craco, here is some code that I used to get things working: 参考文章: github.com/pmmmwh/reac…


const fs = require('fs');
const path = require('path');

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);

module.exports = {
	plugins: [
		{
			plugin: require('craco-babel-loader'),
			options: {
				includes: [resolveApp('../shared')],
			},
		},
	],
};