Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save akinogu/927e2ed1926f2606a960def9adf421b9 to your computer and use it in GitHub Desktop.
Save akinogu/927e2ed1926f2606a960def9adf421b9 to your computer and use it in GitHub Desktop.
## つまりどこ
### github pagesにdemo公開
https://akinogu.github.io/simple-react-slider/
#### 画像が表示されない
`file-loader`と`url-loader`をインストール。
file名を指定したいので、loaderにfile-loaderを指定し、`options.name`も追加。
outputPathも追加。
```js
module.exports = {
output: {
path: path.resolve(__dirname, 'demo/dist'),
filename: 'main.js'
},
entry: './demo/app.js',
resolve: {
extensions: ['.js'],
modules: [path.join(__dirname, 'node_modules')]
},
plugins: [
new HtmlWebpackPlugin({
template: 'demo/index.html'
})
],
devServer: {
port: 3000,
contentBase: './demo',
historyApiFallback: true,
hot: false
},
module: {
rules: [
...
,
// 追記!
{
test: /\.(jpg|png)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}
]
}
]
}
};
```
この設定を加えることで`output.path`に指定しているdirectory配下に`images`ファイルが作成されます。
### npmライブラリとして公開
#### Invalid hook call
error message
```
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
```
おそらく3が原因。
npmライブラリでbuildされるファイルからreactを除外すれば行けるかもしれないと思い、webpackの設定に`externals`の設定を追加。
```js
module.exports = {
output: {
...
},
...
,
module: {
...
},
// ここを追記!
externals: [
{
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDom',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
}
}
]
};
```
このexternalsで定義したライブラリは、importで使用していてもビルドして生成されるbundle.jsには含まれなくなる。
これで試したところエラーが消えた
#### Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
error message
```
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
```
libraryTarget: ライブラリ形式を指定。`umd`を指定すれば良さそう。
libraryExport: defaultしかexportされないようにする
```js
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'umd', // 追記!
libraryExport: 'default' // 追記!
},
...
}
```
これでエラーは出なくなりました。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment