仅导入样式化组件会在浏览器控制台中导致此错误:
styled-components.browser.esm.js?face:1670 Uncaught TypeError: (0 , _react.createContext) is not a function
at Object.eval (styled-components.browser.esm.js?face:1670)
at eval (styled-components.browser.esm.js:2490)
at Object../node_modules/styled-components/dist/styled-components.browser.esm.js (vendors~index.js:167)
at __webpack_require__ (index.js:79)
at eval (index.js?12d5:2)
at Object../src/index.js (index.js:165)
at __webpack_require__ (index.js:79)
at checkDeferredModules (index.js:46)
at index.js:152
at index.js:155
我正在使用webpack,preact,Babel。
在新的空构建中,要重现的代码实际上就是这样:
src / index.js:
import { h, Component, render } from "preact"
import styled from "styled-components"
package.json:
{
"name": "App",
"version": "0.0.1",
"description": "Web app.",
"main": "index.js",
"scripts": {
"build": "rm -rf dist/* && NODE_ENV=development webpack -d --config webpack.conf.js --env development"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"preact": "^8.4.2",
"preact-compat": "^3.18.4",
"styled-components": "^4.1.3",
"webpack": "^4.28.4",
"webpack-cli": "^3.2.1"
},
"dependencies": {}
}
webpack.conf.js:
const path = require("path")
const webpack = require("webpack")
const htmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
entry: {
index: "./src/index.js"
},
module: {
rules: [{
test: /\.(js|jsx)$/i,
use: {
loader: 'babel-loader',
options: {
presets: [
'babel-preset-env',
'babel-preset-react'
],
plugins: [
[ 'babel-plugin-transform-react-jsx', {
pragma: 'h'
}],
]
}
}
}]
},
output: {
publicPath: ("http://your-hostname.com/"),
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
chunkFilename: '[name].js'
},
optimization: {
splitChunks: {
chunks: 'all'
},
occurrenceOrder: true
},
plugins: [
new htmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html'
})
],
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat'
}
}
}
使用npm run build
进行构建可以很好地工作,但是在浏览器中访问生成的页面会产生上述错误。
非常感谢您收到任何指针。
编辑:
根据this issue logged against Preact-CLI,preact没有反应的contextApi
,因此我应该将styled-components
降级为v3,而不是v4。降级确实确实可以解决问题。
尽管令人困惑的是,preact的作者Jason Miller说in a tweet“ preact支持上下文就很好了”。我可能误会了这一点。
答案 0 :(得分:2)
免责声明:我是在做正事。
您看到此错误,因为Preact 8.x不支持createContext
-API。这将是我们即将推出的下一个主要版本的一部分。 Alpha计划于2019年3月4日发布。
如果您绝对需要styled-components
来使用Preact 8.x,那么您唯一的选择就是像建议的@ukosteopath那样降级到styled-components
V3。
答案 1 :(得分:0)
请参见此处https://github.com/developit/preact-cli/issues/672#issuecomment-440985092和我的编辑。
将styled-components
从v4降级到v3可“修复”该问题。