我正在使用带有Babel 7的React和TypeScript创建模块化组件库。
我希望我的库的用户通过类似于下面的语法导入组件:
import SomeComponent from "my-awesome-lib/SomeComponent"
SomeComponent是my-awesome-lib包中的TSX模块:
import * as React from "react";
export default function () {
return <h1>SomeComponent</h1>
}
my-awesome-component的package.json文件的main
字段是:
"main": "src/index.ts"
我不想发布我的组件库的编译版本,因为我在我的组件中导入CSS和其他资产,我希望我的包的所有用户都使用Webpack和一些特定的配置。
现在我的问题是`来自“my-awesome-lib / SomeComponent”的`import SomeComponent'失败并出现解析错误:
ERROR in ../node_modules/wtf/index.tsx 4:9
Module parse failed: Unexpected token (4:9)
You may need an appropriate loader to handle this file type.
|
| export default function () {
> return <h1>WTF</h1>
| }
似乎Webpack不会在node_modules中加载或转换TSX文件。
我在我的用户应用程序的根目录中使用这个tsconifg.json(导入my-awesome-lib):
{
"compilerOptions": {
"outDir": "./dist",
"module": "commonjs",
"target": "es5",
"jsx": "react",
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true,
"downlevelIteration": true,
"lib": ["es5", "es2015", "dom", "scripthost"],
"typeRoots": ["node_modules/@types", "src/@types"],
},
"include": ["src/**/*", "node_modules/**/*"],
"exclude": []
}
而Webpack的相关配置是:
const tsModules = {
test: /\.(js|jsx|ts|tsx)$/,
include: [path.resolve('src')],
exclude: /node_modules/,
loader: 'babel-loader'
}
const resolve = {
alias: {
},
modules: [
'node_modules'
],
extensions: ['.tsx', '.ts', '.js']
}
module.exports = {
...
context: resolve('src'),
resolve: resolve,
module: {
rules: [
tsModules,
...
]
}
}
如何让Webpack从node_modules加载和转换my-awesome-lib的TSX模块?
你排除你的node_modules
目录(通常是一件好事):
const tsModules = {
test: /\.(js|jsx|ts|tsx)$/,
include: [path.resolve('src')],
exclude: /node_modules/,
loader: 'babel-loader'
}
除了明确排除node_modules
文件夹之外,由于你在src
中的babel-loader
属性,你也只允许include
处理tsModules
文件夹的内容。所以这个错误:
错误在../node_modules/wtf/index.tsx 4:9模块解析失败:意外的令牌(4:9)
说得通。
如果删除node_modules
属性并在tsModules.include
中更改正则表达式,您仍然可以排除tsModules.exclude
除了单个文件夹:
const tsModules = {
// ...
exclude: /node_modules\/(?!my-awesome-lib)\/*/
// ...
}
或者你可以,但我尚未测试它,将my-awesome-lib
目录添加到include
数组:
const tsModules = {
// ...
include: [
path.resolve(__dirname, './src'),
path.resolve(__dirname, './node-modules/my-awesome-lib')
]
// ...
}
然后node_modules/my-awesome-lib
目录中的文件将传递babel-loader
,它将转换typescript代码。
编辑:我认为你混淆来自你的tsconfig.json
文件与"include": ["src/**/*", "node_modules/**/*"],
。 Babel正在编写代码,而不是打字稿。因此,在根目录中有一个tsconfig.json
文件可能对您的IDE有所帮助(特别是如果您使用的是Microsoft的VScode),但对babel
和@babel/preset-typescript
如何转换代码没有影响。
此设置假设您使用样式组件并且没有css / scss。
这里重要的是你有“模块”:你的tsconfig中的commonJS和你的webpack配置中的libraryTarget:“commonJS”。 Externals告诉webpack不要将您的库与React,或React-DOM或样式组件捆绑在一起,而是在您要导入的项目中查找这些包。
你还需要从你的package.json依赖项中获取React,react-dom和样式组件,并将这些包放在你的peer-dependencies中
const path = require("path");
const fs = require("fs");
const TerserPlugin = require('terser-webpack-plugin');
const appIndex = path.join(__dirname, "../src/main.tsx");
const appBuild = path.join(__dirname, "../storybook-static");
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');
module.exports = {
context: fs.realpathSync(process.cwd()),
mode: "production",
bail: true,
devtool: false,
entry: appIndex,
output: {
path: appBuild,
filename: "dist/Components.bundle.js",
publicPath: "/",
libraryTarget: "commonjs"
},
externals: {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
},
"styled-components": {
root: "styled-components",
commonjs2: "styled-components",
commonjs: "styled-components",
amd: "styled-components"
}
},
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
parse: {
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
comparisons: false,
inline: 2,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
ascii_only: true,
},
},
parallel: true,
cache: true,
sourceMap: false,
})
],
},
resolve: {
extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx", ".ts", ".tsx"],
alias: {
"react-native": "react-native-web",
},
},
module: {
strictExportPresence: true,
rules: [
{ parser: { requireEnsure: false } },
{
test: /\.(ts|tsx)$/,
loader: require.resolve("tslint-loader"),
enforce: "pre",
},
{
oneOf: [
{
test: /\.(tsx?)$/,
loader: require.resolve('awesome-typescript-loader'),
options: {
configFileName: 'tsconfig.prod.json'
}
},
],
},
],
},
plugins: [
new TsConfigPathsPlugin()
],
node: {
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty",
},
performance: false,
};
注意:将应用程序中的某个点定位为仅包含要导出的组件的条目非常重要。
I.E对我来说,它是Main.tsx,在Main.tsx里面看起来像这样。
export { Checkbox } from "./components/Checkbox/Checkbox";
export { ColorUtils } from "./utils/color/color";
export { DataTable } from "./components/DataTable/DataTable";
export { DatePicker } from "./components/DateTimePicker/DatePicker/DatePicker";
export { DateTimePicker } from "./components/DateTimePicker/DateTimePicker/DateTimePicker";
export { Disclosure } from "./components/Disclosure/Disclosure";
这意味着webpack不会捆绑您不想导出的内容。为了测试你的捆绑工作,尝试从bundle中导入带有require语法的东西来绕过typescript typings并在tsconfig中转换allowJS true。
像const Button = require(“../ path / to / js / bundle”)。Button console.log(Button);
我发现create-react-library
非常有帮助