仅导入样式化组件会在浏览器控制台中导致此错误:
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没有react的
contextApi
,因此我应该将styled-components
降级为v3,而不是v4。降级确实确实可以解决该问题。令人困惑的是,preact的作者Jason Miller说in a tweet“ preact支持上下文就很好了”。我可能误会了这一点。
最佳答案
免责声明:我从事预言工作。
您看到此错误的原因是Preact 8.x不支持createContext
-API。这将是我们即将发布的下一个主要版本的一部分。我们目前处于测试版状态,希望很快就可以发布候选版本。
如果您绝对需要styled-components
来使用Preact 8.x,那么您唯一的选择是像建议的@ukosteopath一样降级到styled-components
V3。
关于webpack - 对样式化组件进行预先处理会导致浏览器控制台出现错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54218013/