[英]import in third party library breaks build
我發布了一個 package 文件結構如下:
.
├── index.css
├── index.tsx
├── node_modules
├── package.json
└── yarn.lock
index.tsx 文件正在導入 index.css 文件,如下所示:
import React from 'react'
import './index.css'
export const CustomComponent = ()=> {
return <span>Hello World</span>
}
命令tc
生成一個build
目錄。 在 package.json 文件中,我有以下內容:
{
...
"main": "./build/index.js",
"types": "./build/index.d.ts",
"files": [
"build/**/*",
],
...
}
一旦安裝了我的 package,您可以在項目 node_modules 目錄中設置與上述相同的文件結構。
現在安裝 package 的項目無法構建,因為它無法識別來自 package index.ts 文件的路徑./index.css
8CBA22E28EB17B5F5C6AE2A266AZ
知道如何解決這個問題嗎?
它不起作用,因為文件index.css
在 package 的根目錄中不存在,而是在build/index.css
下。
當您使用npm publish
package 時,它會維護文件夾結構。 The main
in package.json
simply points to the default file in your package, it doesn't make /build
the root folder of your package.
為了解決這個問題,要么從mypackage/build/index.css
(不太理想),要么從build
文件夾中調用npm publish
,而不是從父文件夾中發布。
我通過使用 Rollup 解決了這個問題。 查看匯總,typescript 配置和 package.json 文件如下:
// tsconfig.json
{
"compilerOptions": {
"jsx": "react",
"target": "es5",
"module": "esnext",
"sourceMap": true,
"allowJs": false,
"moduleResolution": "node",
"declaration": true,
"outDir": "build",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"downlevelIteration": true,
"forceConsistentCasingInFileNames": true,
"lib": ["es6", "dom", "es2016", "es2017"]
},
"include": ["src"],
"exclude": ["node_modules", "build"]
}
// rollup.config.js
import typescript from "rollup-plugin-typescript2";
import commonjs from "rollup-plugin-commonjs";
import external from "rollup-plugin-peer-deps-external";
import resolve from "rollup-plugin-node-resolve";
import postcss from 'rollup-plugin-postcss';
import json from '@rollup/plugin-json';
import nodeExternal from '@yelo/rollup-node-external';
import pkg from "./package.json";
export default {
input: "src/index.ts",
output: [
{
file: pkg.main,
format: "cjs",
exports: "named",
sourcemap: true
},
{
file: pkg.module,
format: "es",
exports: "named",
sourcemap: true
}
],
plugins: [
external(),
resolve(),
typescript({
rollupCommonJSResolveHack: true,
exclude: "**/__tests__/**",
clean: true
}),
commonjs({
include: ["node_modules/**"],
exclude: ["./src/index.css"],
namedExports: {
"node_modules/react/react.js": [
"Children",
"Component",
"PropTypes",
"createElement"
],
"node_modules/react-dom/index.js": ["render"]
}
}),
json(),
postcss({
plugins: []
})
],
external: nodeExternal()
};
// package.json
{
...
"main": "build/index.js",
"types": "./build/index.d.ts",
"files": [
"build/**/*"
],
"module": "build/index.es.js",
"jsnext:main": "build/index.es.js",
"scripts": {
"build": "rollup -c",
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.