css$/i, use: ['style-loader', 'css-loader'] } ] }, // When importing a module whose path matches one of the following, just // assume a corresponding global variable exists and use that instead.

1 month ago 3 Replies
曾柏翰
2 years ago

[請益]

各位大神大家好

我目前負責的專案有一個 react 的 component 會用 webpack 產出一個 js 檔
讓其他人可以在 html 中引入,目前這樣可以成功
但想問的事有沒有辦法將 component 產成一隻 js 檔
並在其他 react 專案中引入呢?或是我的 webpack.config.js 應該要怎麼改?

webpack.config.js:
const TerserPlugin = require('terser-webpack-plugin');
const config = {
mode: "production", // development || production || none
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{
test: /.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /.js$/,
loader: "source-map-loader"
},
{
test: /.css$/i,
use: ['style-loader', 'css-loader']
}
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
},
output: {
filename: 'index.js'
}
};
module.exports = (env, argv) => {
// 如果是 production 移除掉所有的 console.log
if (config.mode === 'production') {
config.optimization = {
minimizer: [
new TerserPlugin({
sourceMap: true, // Must be set to true if using source-maps in production
terserOptions: {
compress: {
drop_console: true
}
}
})
]
}
}
return config;
};

目前直接用原本的方式產出的 js 檔引入會出現

 Expected an assignment or function call and instead saw an expression  no-unused-expressions

的錯誤

0 Likes

Replies

Tangent Chang 2 years ago

可能可以參考這兩個stackoverflow,其他資訊可以google "webpack build react component"。 https://stackoverflow.com/questions/56141305/use-webpack-to-bundle-a-react-component-to-be-imported-by-another-react-componen https://stackoverflow.com/questions/56970495/build-react-components-library-with-webpack-4

1 Like
Chi-Feng Chen 2 years ago

可以,我們是用 rollup 編成一個 package 上傳到 private NPM 要用的人就從 private NPM 像 npm i 一樣 加到自己的專案裡 可以參考 Nexus 或 JFrog 至於怎麼編就深了 可以去查怎麼做成 CommonJS 的 library 以及怎麼在 package.json 設定 main / es:main / files

3 Likes
曾柏翰 (2 years ago)

陳其灃 感謝🙏我再研究看看